Sha256: dc42dff58e32fce3b4ef6816b59de0c7307c527ecd6b19533e6ae0f8fa5eeae5

Contents?: true

Size: 1.42 KB

Versions: 3

Compression:

Stored size: 1.42 KB

Contents

module ActiveModel::Serializer::Utils
  module_function

  # 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: {} } } }`.
  #
  # @param [String] included
  # @return [Hash] a Hash representing the same tree structure
  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

  # 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: {} } } }`.
  #
  # @param [Symbol, Hash, Array, String] included
  # @return [Hash] a Hash representing the same tree structure
  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
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
active_model_serializers-0.10.0.rc3 lib/active_model/serializer/utils.rb
cheap_ams-0.10.11 lib/active_model/serializer/utils.rb
cheap_ams-0.10.10 lib/active_model/serializer/utils.rb