Skip to content

Commit 6ea8dcb

Browse files
committed
Add if/unless support to attributes.
1 parent 136cd21 commit 6ea8dcb

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed
Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,24 @@
11
module ActiveModel
22
class Serializer
3-
Attribute = Struct.new(:name, :key, :block) do
3+
Attribute = Struct.new(:name, :key, :block, :condition_type, :condition) do
44
def value(serializer)
55
if block
66
serializer.instance_eval(&block)
77
else
88
serializer.read_attribute_for_serialization(name)
99
end
1010
end
11+
12+
def include?(serializer)
13+
case condition_type
14+
when :if
15+
serializer.send(condition)
16+
when :unless
17+
!serializer.send(condition)
18+
else
19+
true
20+
end
21+
end
1122
end
1223
end
1324
end

lib/active_model/serializer/attributes.rb

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ module Attributes
77
with_options instance_writer: false, instance_reader: false do |serializer|
88
serializer.class_attribute :_attributes_data # @api private
99
self._attributes_data ||= {}
10+
serializer.class_attribute :_attributes_conditions # @api private
11+
self._attributes_conditions ||= {}
1012
end
1113

1214
autoload :Attribute
@@ -16,6 +18,7 @@ module Attributes
1618
def attributes(requested_attrs = nil, reload = false)
1719
@attributes = nil if reload
1820
@attributes ||= self.class._attributes_data.values.each_with_object({}) do |attr, hash|
21+
next unless attr.include?(self)
1922
next unless requested_attrs.nil? || requested_attrs.include?(attr.key)
2023
hash[attr.key] = attr.value(self)
2124
end
@@ -53,7 +56,16 @@ def attributes(*attrs)
5356
# end
5457
def attribute(attr, options = {}, &block)
5558
key = options.fetch(:key, attr)
56-
_attributes_data[attr] = Attribute.new(attr, key, block)
59+
condition_type =
60+
if options.key?(:if)
61+
:if
62+
elsif options.key?(:unless)
63+
:unless
64+
else
65+
:none
66+
end
67+
condition = options[condition_type]
68+
_attributes_data[attr] = Attribute.new(attr, key, block, condition_type, condition)
5769
end
5870

5971
# @api private

0 commit comments

Comments
 (0)