Module: ActiveModel::Serializer::IncludeTree::Parsing

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

Class Method Summary (collapse)

Class Method Details

+ (Hash) include_args_to_hash(included)

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.

Examples:

`posts: [:author, comments: [:author, :upvotes]]`

would become

 `{ posts: { author: {}, comments: { author: {}, upvotes: {} } } }`.
`[:author, :comments => [:author]]`

 would become

 `{:author => {}, :comments => { author: {} } }`

Parameters:

  • included (Symbol, Hash, Array, String)

Returns:

  • (Hash)

    a Hash representing the same tree structure



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/active_model/serializer/include_tree.rb', line 46

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

+ (Hash) include_string_to_hash(included)

Translates a comma separated list of dot separated paths (JSON API format) into a Hash.

Examples:

`'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



19
20
21
22
23
24
25
# File 'lib/active_model/serializer/include_tree.rb', line 19

def include_string_to_hash(included)
  # TODO: Needs comment walking through the process of what all this is doing.
  included.delete(' ').split(',').reduce({}) do |hash, path|
    include_tree = path.split('.').reverse_each.reduce({}) { |a, e| { e.to_sym => a } }
    hash.deep_merge!(include_tree)
  end
end