Skip to content

Commit

Permalink
Adding optional type for attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
MattRogish committed Dec 11, 2012
1 parent 6780cd3 commit 25c564b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
12 changes: 9 additions & 3 deletions lib/active_model/serializer.rb
Expand Up @@ -73,7 +73,9 @@ def attributes(*attrs)
end

def attribute(attr, options={})
self._attributes = _attributes.merge(attr => options[:key] || attr.to_s.gsub(/\?$/, '').to_sym)
self._attributes = _attributes.merge(attr.is_a?(Hash) ? attr : {attr => options[:key] || attr.to_s.gsub(/\?$/, '').to_sym})

attr = attr.keys[0] if attr.is_a? Hash

unless method_defined?(attr)
define_method attr do
Expand Down Expand Up @@ -175,8 +177,12 @@ def schema
attrs[key] = column.type
else
# Computed attribute (method on serializer or model). We cannot
# infer the type, so we put nil.
attrs[key] = nil
# infer the type, so we put nil, unless specified in the attribute declaration
if name != key
attrs[name] = key
else
attrs[key] = nil
end
end
end

Expand Down
6 changes: 3 additions & 3 deletions test/serializer_test.rb
Expand Up @@ -493,14 +493,14 @@ class << self; self; end.class_eval do
def can_edit; end
def drafts; end

attributes :name, :age, :can_edit
attributes :name, :age, :can_edit => :boolean
has_many :posts, :serializer => Class.new
has_many :drafts, :serializer => Class.new
has_one :parent, :serializer => Class.new
end

assert_equal serializer.schema, {
:attributes => { :name => :string, :age => :integer, :can_edit => nil },
:attributes => { :name => :string, :age => :integer, :can_edit => :boolean },
:associations => {
:posts => { :has_many => :posts },
:drafts => nil,
Expand Down Expand Up @@ -1004,7 +1004,7 @@ def self.to_s
:name => 'logo.png',
:url => 'http://example.com/logo.png',
:attachable => {
:type => :email,
:type => :email,
:id => 1
}},
:emails => [{
Expand Down

0 comments on commit 25c564b

Please sign in to comment.