Adds support for namespace options

This commit is contained in:
John Allen 2013-05-15 20:42:10 -04:00
parent 2f69f318e0
commit e5cf9bdf8c
3 changed files with 39 additions and 9 deletions

View file

@ -64,7 +64,7 @@ Grape::Formatter::ActiveModelSerializers.infer_serializers = false
```
### Manually specifying a serializer
### Manually specifying serializer options
Serializers can be specified at a route level by with the serializer option. A serializer can be specified by passing the the serializer class or the serializer name. The following are equivalent:
@ -81,6 +81,27 @@ get "/home", :serializer => :home
...
```
You can also set a serializer at the namespace level. This serializer can/will be overriden if a serilizer is also specified on the route.
```ruby
namespace 'foo', :serializer => :bar do
get "/" do
# will use "bar" serializer
end
get "/home", :serializer => :home do
# will use "home" serializer
end
end
```
Other standard options for `ActiveModel::Serializers` can be provided at either the namespace or route level with the same overriding behavior.
```ruby
get "/home", :root => 'world', :each_serializer => :fancy_home
...
```
### Example

View file

@ -6,14 +6,17 @@ module Grape
module ActiveModelSerializers
class << self
attr_accessor :infer_serializers
attr_reader :env
attr_reader :endpoint
ActiveModelSerializers.infer_serializers = true
def call(resource, env)
# @object = object
options = env['api.endpoint'].options[:route_options]
@endpoint = env["api.endpoint"]
namespace = endpoint.settings[:namespace]
namespace_options = namespace ? namespace.options : {}
route_options = endpoint.options[:route_options]
options = namespace_options.merge(route_options)
serializer = serializer(endpoint, resource, options)
@ -24,14 +27,9 @@ module Grape
end
end
# options = endpoint.options[:route_options][:serializer_options] || {}
# serializer.new(object, options).to_json
# end
private
def serializer(endpoint, resource, options={})
serializer = options.delete(:serializer) ||
(resource.respond_to?(:active_model_serializer) &&
resource.active_model_serializer)

View file

@ -74,6 +74,17 @@ describe Grape::ActiveModelSerializers do
end
end
it "uses namespace options when provided" do
subject.namespace :admin, :serializer => UserSerializer do
get('/jeff') do
User.new(first_name: 'Jeff')
end
end
get "/admin/jeff"
last_response.body.should == "{\"user\":{\"first_name\":\"Jeff\",\"last_name\":null}}"
end
# [User2Serializer, 'user2', :user2].each do |serializer|
# it "should render using serializer (#{serializer})" do
# subject.get("/home", serializer: serializer) do