Skip to content

Using Boxer with Rails

Brad Fults edited this page Oct 18, 2011 · 1 revision

Installation

Just include the boxer gem in your Gemfile:

gem 'boxer'

Then run bundle install to install the gem.

Configuration

It's recommended to use a Rails initializer to configure Boxer, usually config/initializers/boxer.rb.

Including URL Generation Methods

# Make URL helpers available in all boxes
Boxer.configure do |config|
  config.box_includes = [Rails.application.routes.url_helpers]
end

Now you can use those URL generation methods inside of all your boxes without thinking twice:

Boxer.box(:user) do |box, user|
  {
    :name => user.name,
    :url  => user_path(user),
  }
end

Defining Boxes for Different Objects

# Load all of our boxes
unless Rails.env.test?
  Dir[File.join(Rails.root, 'lib', 'boxer', '**', '*.rb')].each do |f|
    require_dependency f
  end
end

Using that code, you can create a Ruby file for each box inside lib/boxer/. So your User box could be defined in lib/boxer/user.rb.

Rendering with Boxer

In your API actions, simply render JSON from Boxer:

def index
  @users = Users.all.limit(10)
  render :json => @users.map { |u| Boxer.ship(:user, u) }
end