diff --git a/README.md b/README.md index fd1bc9a..584b528 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/lib/grape-active_model_serializers/formatter.rb b/lib/grape-active_model_serializers/formatter.rb index 2f4ce79..cd86dda 100644 --- a/lib/grape-active_model_serializers/formatter.rb +++ b/lib/grape-active_model_serializers/formatter.rb @@ -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) diff --git a/spec/grape_ams_spec.rb b/spec/grape_ams_spec.rb index 7bc2c64..d7845fa 100644 --- a/spec/grape_ams_spec.rb +++ b/spec/grape_ams_spec.rb @@ -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