Module: ActiveModel::Serializer::Utils

Defined in:
lib/active_model/serializer/utils.rb

Class Method Summary collapse

Class Method Details

.include_args_to_hash(included) ⇒ Hash

Translates the arguments passed to the include option into a Hash. The format can be either a String (see #include_string_to_hash), an Array of Symbols and Hashes, or a mix of both. Example: ‘posts: [:author, comments: [:author, :upvotes]]` would become `{ posts: { author: {}, comments: { author: {}, upvotes: {} } } }`.

Parameters:

  • included (Symbol, Hash, Array, String)

Returns:

  • (Hash)

    a Hash representing the same tree structure



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/active_model/serializer/utils.rb', line 21

def include_args_to_hash(included)
  case included
  when Symbol
    { included => {} }
  when Hash
    included.each_with_object({}) { |(key, value), hash| hash[key] = include_args_to_hash(value) }
  when Array
    included.inject({}) { |a, e| a.merge!(include_args_to_hash(e)) }
  when String
    include_string_to_hash(included)
  else
    {}
  end
end

.include_string_to_hash(included) ⇒ Hash

Translates a comma separated list of dot separated paths (JSONAPI format) into a Hash. Example: ‘’posts.author, posts.comments.upvotes, posts.comments.author’‘ would become `{ posts: { author: {}, comments: { author: {}, upvotes: {} } } }`.

Parameters:

  • included (String)

Returns:

  • (Hash)

    a Hash representing the same tree structure



9
10
11
12
13
# File 'lib/active_model/serializer/utils.rb', line 9

def include_string_to_hash(included)
  included.delete(' ').split(',').inject({}) do |hash, path|
    hash.deep_merge!(path.split('.').reverse_each.inject({}) { |a, e| { e.to_sym => a } })
  end
end