Module: Grape::Formatter::ActiveModelSerializers

Defined in:
lib/grape-active_model_serializers/formatter.rb

Class Method Summary collapse

Class Method Details

.build_options_from_endpoint(endpoint) ⇒ Object



38
39
40
# File 'lib/grape-active_model_serializers/formatter.rb', line 38

def build_options_from_endpoint(endpoint)
  [endpoint.default_serializer_options || {}, endpoint.namespace_options, endpoint.route_options, endpoint.options, endpoint.options.fetch(:route_options)].reduce(:merge)
end

.call(resource, env) ⇒ Object



5
6
7
8
9
10
11
12
13
# File 'lib/grape-active_model_serializers/formatter.rb', line 5

def call(resource, env)
  serializer = fetch_serializer(resource, env)

  if serializer
    serializer.to_json
  else
    Grape::Formatter::Json.call resource, env
  end
end

.default_root(endpoint) ⇒ Object

array root is the innermost namespace name (‘space’) if there is one, otherwise the route name (e.g. get ‘name’)



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/grape-active_model_serializers/formatter.rb', line 44

def default_root(endpoint)
  innermost_scope = if endpoint.respond_to?(:namespace_stackable)
                      endpoint.namespace_stackable(:namespace).last
                    else
                      endpoint.settings.peek[:namespace]
                    end

  if innermost_scope
    innermost_scope.space
  else
    endpoint.options[:path][0].to_s.split('/')[-1]
  end
end

.fetch_serializer(resource, env) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/grape-active_model_serializers/formatter.rb', line 15

def fetch_serializer(resource, env)
  endpoint = env['api.endpoint']
  options = build_options_from_endpoint(endpoint)

  serializer = options.fetch(:serializer, ActiveModel::Serializer.serializer_for(resource))
  return nil unless serializer

  options[:scope] = endpoint unless options.key?(:scope)
  # ensure we have an root to fallback on
  options[:resource_name] = default_root(endpoint) if resource.respond_to?(:to_ary)
  serializer.new(resource, options.merge(other_options(env)))
end

.other_options(env) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/grape-active_model_serializers/formatter.rb', line 28

def other_options(env)
  options = {}
  ams_meta = env['ams_meta'] || {}
  meta =  ams_meta.delete(:meta)
  meta_key = ams_meta.delete(:meta_key)
  options[:meta_key] = meta_key if meta && meta_key
  options[meta_key || :meta] = meta if meta
  options
end