mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
Add support for if/unless on attributes.
This commit is contained in:
parent
adaf5b87df
commit
a502b5d38b
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
Loading…
Reference in New Issue
Block a user