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



61
62
63
# File 'lib/grape-active_model_serializers/formatter.rb', line 61

def build_options_from_endpoint(endpoint)
  endpoint.namespace_options.merge(endpoint.route_options)
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’)



67
68
69
70
71
72
73
74
75
# File 'lib/grape-active_model_serializers/formatter.rb', line 67

def default_root(endpoint)
  innermost_scope = endpoint.settings.peek

  if innermost_scope[:namespace]
    innermost_scope[:namespace].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
# 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)

  if resource.respond_to?(:to_ary) && !resource.empty?
    # ensure we have an root to fallback on
    endpoint.controller_name = default_root(endpoint)
  end

  ::ActiveModel::Serializer.build_json(endpoint,
                                       resource,
                                       options.merge(other_options)
                                      )
end

.metaObject



45
46
47
# File 'lib/grape-active_model_serializers/formatter.rb', line 45

def meta
  @meta_content_items || {}
end

.meta=(meta_content) ⇒ Object



49
50
51
# File 'lib/grape-active_model_serializers/formatter.rb', line 49

def meta=(meta_content)
  @meta_content_items = { meta: meta_content } if meta_content
end

.meta_keyObject



53
54
55
# File 'lib/grape-active_model_serializers/formatter.rb', line 53

def meta_key
  @meta_key || {}
end

.meta_key=(key) ⇒ Object



57
58
59
# File 'lib/grape-active_model_serializers/formatter.rb', line 57

def meta_key=(key)
  @meta_key = { meta_key: key } if key
end

.other_optionsObject



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

def other_options
  options = {}
  if @meta_content_items
    meta_option = @meta_content_items[:meta]
    @meta_content_items.delete(:meta)
    options[:meta] = meta_option if meta_option
    if @meta_key
     key_option = @meta_key[:meta_key]
      @meta_key.delete(:meta_key)
      options[:meta_key] = key_option if key_option
    end
  end
  options
end