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



42
43
44
# File 'lib/grape-active_model_serializers/formatter.rb', line 42

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’)



48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/grape-active_model_serializers/formatter.rb', line 48

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
27
28
29
30
# 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)
  ams_options = {}.tap do |ns|
    # Extracting declared version from Grape
    ns[:namespace] = options[:version].try(:classify) if options.try(:[], :version)
  end

  serializer = options.fetch(:serializer, ActiveModel::Serializer.serializer_for(resource, ams_options))
  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



32
33
34
35
36
37
38
39
40
# File 'lib/grape-active_model_serializers/formatter.rb', line 32

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