Skip to content

Commit

Permalink
Merge pull request #138 from tchak/meta
Browse files Browse the repository at this point in the history
Meta object
  • Loading branch information
steveklabnik committed Dec 10, 2012
2 parents 3fdd4bb + a71698d commit 6780cd3
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/active_model/array_serializer.rb
Expand Up @@ -35,6 +35,14 @@ def serializable_array
end
end

def meta_key
@options[:meta_key].try(:to_sym) || :meta
end

def include_meta(hash)
hash[meta_key] = @options[:meta] if @options.has_key?(:meta)
end

def as_json(*args)
@options[:hash] = hash = {}
@options[:unique_values] = {}
Expand All @@ -49,6 +57,8 @@ def as_json(*args)

if root = @options[:root]
hash.merge!(root => array)
include_meta hash
hash
else
array
end
Expand Down
9 changes: 9 additions & 0 deletions lib/active_model/serializer.rb
Expand Up @@ -242,6 +242,14 @@ def url_options
@options[:url_options] || {}
end

def meta_key
@options[:meta_key].try(:to_sym) || :meta
end

def include_meta(hash)
hash[meta_key] = @options[:meta] if @options.has_key?(:meta)
end

# Returns a json representation of the serializable
# object including the root.
def as_json(options={})
Expand All @@ -250,6 +258,7 @@ def as_json(options={})
@options[:unique_values] = {}

hash.merge!(root => serializable_hash)
include_meta hash
hash
else
serializable_hash
Expand Down
46 changes: 46 additions & 0 deletions test/serializer_test.rb
Expand Up @@ -1192,4 +1192,50 @@ def tests_includes_does_not_include_nil_polymoprhic_associations
}
}, actual)
end

def test_meta_key_serialization
tag_serializer = Class.new(ActiveModel::Serializer) do
attributes :name
end

tag_class = Class.new(Model) do
def name
@attributes[:name]
end

define_method :active_model_serializer do
tag_serializer
end
end

serializable_array = Class.new(Array)

array = serializable_array.new
array << tag_class.new(:name => 'Rails')
array << tag_class.new(:name => 'Sinatra')

actual = array.active_model_serializer.new(array, :root => :tags, :meta => {:total => 10}).as_json

assert_equal({
:meta => {
:total => 10,
},
:tags => [
{ :name => "Rails" },
{ :name => "Sinatra" },
]
}, actual)

actual = array.active_model_serializer.new(array, :root => :tags, :meta => {:total => 10}, :meta_key => 'meta_object').as_json

assert_equal({
:meta_object => {
:total => 10,
},
:tags => [
{ :name => "Rails" },
{ :name => "Sinatra" },
]
}, actual)
end
end

0 comments on commit 6780cd3

Please sign in to comment.