Skip to content

Commit bcd428e

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

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed
Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,38 @@
11
module ActiveModel
22
class Serializer
3-
Attribute = Struct.new(:name, :key, :block) do
3+
Attribute = Struct.new(:name, :block, :key, :condition_type, :condition) do
4+
def initialize(name, block, options)
5+
super(name, block)
6+
self.key = options.fetch(:key, name)
7+
self.condition_type =
8+
if options.key?(:if)
9+
:if
10+
elsif options.key?(:unless)
11+
:unless
12+
else
13+
:none
14+
end
15+
self.condition = options[condition_type]
16+
end
17+
418
def value(serializer)
519
if block
620
serializer.instance_eval(&block)
721
else
822
serializer.read_attribute_for_serialization(name)
923
end
1024
end
25+
26+
def include?(serializer)
27+
case condition_type
28+
when :if
29+
serializer.send(condition)
30+
when :unless
31+
!serializer.send(condition)
32+
else
33+
true
34+
end
35+
end
1136
end
1237
end
1338
end

lib/active_model/serializer/attributes.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ module Attributes
1616
def attributes(requested_attrs = nil, reload = false)
1717
@attributes = nil if reload
1818
@attributes ||= self.class._attributes_data.values.each_with_object({}) do |attr, hash|
19+
next unless attr.include?(self)
1920
next unless requested_attrs.nil? || requested_attrs.include?(attr.key)
2021
hash[attr.key] = attr.value(self)
2122
end
@@ -52,8 +53,7 @@ def attributes(*attrs)
5253
# object.edits.last(5)
5354
# end
5455
def attribute(attr, options = {}, &block)
55-
key = options.fetch(:key, attr)
56-
_attributes_data[attr] = Attribute.new(attr, key, block)
56+
_attributes_data[attr] = Attribute.new(attr, block, options)
5757
end
5858

5959
# @api private

0 commit comments

Comments
 (0)