mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-24 14:56: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
|
module ActiveModel
|
||||||
class Serializer
|
class Serializer
|
||||||
Attribute = Struct.new(:name, :block) do
|
Attribute = Struct.new(:name, :options, :block) do
|
||||||
def value(serializer)
|
def value(serializer)
|
||||||
if block
|
if block
|
||||||
serializer.instance_eval(&block)
|
serializer.instance_eval(&block)
|
||||||
@ -8,6 +8,33 @@ module ActiveModel
|
|||||||
serializer.read_attribute_for_serialization(name)
|
serializer.read_attribute_for_serialization(name)
|
||||||
end
|
end
|
||||||
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
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@ -17,6 +17,7 @@ module ActiveModel
|
|||||||
def attributes(requested_attrs = nil, reload = false)
|
def attributes(requested_attrs = nil, reload = false)
|
||||||
@attributes = nil if reload
|
@attributes = nil if reload
|
||||||
@attributes ||= self.class._attributes_data.each_with_object({}) do |(key, attr), hash|
|
@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)
|
next unless requested_attrs.nil? || requested_attrs.include?(key)
|
||||||
hash[key] = attr.value(self)
|
hash[key] = attr.value(self)
|
||||||
end
|
end
|
||||||
@ -54,7 +55,7 @@ module ActiveModel
|
|||||||
# end
|
# end
|
||||||
def attribute(attr, options = {}, &block)
|
def attribute(attr, options = {}, &block)
|
||||||
key = options.fetch(:key, attr)
|
key = options.fetch(:key, attr)
|
||||||
_attributes_data[key] = Attribute.new(attr, block)
|
_attributes_data[key] = Attribute.new(attr, options, block)
|
||||||
end
|
end
|
||||||
|
|
||||||
# @api private
|
# @api private
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user