Skip to content

Commit

Permalink
Add support for customizing fields
Browse files Browse the repository at this point in the history
  • Loading branch information
wycats committed May 17, 2012
1 parent 33d4842 commit 0f1ec7a
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/active_model/serializer.rb
Expand Up @@ -246,12 +246,16 @@ def attributes(*attrs)
self._attributes = _attributes.dup

attrs.each do |attr|
self._attributes[attr] = attr
attribute attr
end
end

def attribute(attr, options={})
self._attributes = _attributes.merge(attr => options[:key] || attr)

unless method_defined?(attr)
class_eval "def #{attr}() object.read_attribute_for_serialization(:#{attr}) end", __FILE__, __LINE__
end
end

def associate(klass, attrs) #:nodoc:
Expand Down Expand Up @@ -490,11 +494,15 @@ def attributes
hash = {}

_attributes.each do |name,key|
hash[key] = @object.read_attribute_for_serialization(name)
hash[key] = read_attribute_for_serialization(name)
end

hash
end

def read_attribute_for_serialization(name)
send name
end
end
end

Expand Down
54 changes: 54 additions & 0 deletions test/serializer_test.rb
Expand Up @@ -814,4 +814,58 @@ def test_embed_with_include_inserts_at_root
]
}, actual)
end

def test_can_customize_attributes
serializer = Class.new(ActiveModel::Serializer) do
attributes :title, :body

def title
object.title.upcase
end
end

klass = Class.new do
def read_attribute_for_serialization(name)
{ :title => "New post!", :body => "First post body" }[name]
end

def title
read_attribute_for_serialization(:title)
end

def body
read_attribute_for_serialization(:body)
end
end

object = klass.new

actual = serializer.new(object, :root => :post).as_json

assert_equal({
:post => {
:title => "NEW POST!",
:body => "First post body"
}
}, actual)
end

def test_can_customize_attributes_with_read_attributes
serializer = Class.new(ActiveModel::Serializer) do
attributes :title, :body

def read_attribute_for_serialization(name)
{ :title => "New post!", :body => "First post body" }[name]
end
end

actual = serializer.new(Object.new, :root => :post).as_json

assert_equal({
:post => {
:title => "New post!",
:body => "First post body"
}
}, actual)
end
end

0 comments on commit 0f1ec7a

Please sign in to comment.