Add support for if/unless on attributes.

This commit is contained in:
Lucas Hosseini 2015-12-30 17:19:50 +01:00
parent adaf5b87df
commit a502b5d38b
2 changed files with 30 additions and 2 deletions

View File

@ -1,6 +1,6 @@
module ActiveModel
class Serializer
Attribute = Struct.new(:name, :block) do
Attribute = Struct.new(:name, :options, :block) do
def value(serializer)
if block
serializer.instance_eval(&block)
@ -8,6 +8,33 @@ module ActiveModel
serializer.read_attribute_for_serialization(name)
end
end
def included?(serializer)
case condition
when :if
serializer.public_send(condition)
when :unless
!serializer.public_send(condition)
else
true
end
end
private
def condition_type
if options.key?(:if)
:if
elsif options.key?(:unless)
:unless
else
:none
end
end
def condition
options[condition_type]
end
end
end
end

View File

@ -17,6 +17,7 @@ module ActiveModel
def attributes(requested_attrs = nil, reload = false)
@attributes = nil if reload
@attributes ||= self.class._attributes_data.each_with_object({}) do |(key, attr), hash|
next unless attr.included?(self)
next unless requested_attrs.nil? || requested_attrs.include?(key)
hash[key] = attr.value(self)
end
@ -54,7 +55,7 @@ module ActiveModel
# end
def attribute(attr, options = {}, &block)
key = options.fetch(:key, attr)
_attributes_data[key] = Attribute.new(attr, block)
_attributes_data[key] = Attribute.new(attr, options, block)
end
# @api private