@@ -33,6 +33,8 @@ class Serializer
33
33
self . _attributes ||= [ ]
34
34
class_attribute :_attributes_keys
35
35
self . _attributes_keys ||= { }
36
+ class_attribute :_attributes_conditions
37
+ self . _attributes_conditions ||= { }
36
38
serializer . class_attribute :_cache
37
39
serializer . class_attribute :_fragmented
38
40
serializer . class_attribute :_cache_key
@@ -45,6 +47,7 @@ class Serializer
45
47
def self . inherited ( base )
46
48
base . _attributes = _attributes . dup
47
49
base . _attributes_keys = _attributes_keys . dup
50
+ base . _attributes_conditions = _attributes_conditions . dup
48
51
base . _cache_digest = digest_caller_file ( caller . first )
49
52
super
50
53
end
@@ -54,10 +57,11 @@ def self.type(type)
54
57
end
55
58
56
59
def self . attributes ( *attrs )
60
+ options = attrs . last . class == Hash ? attrs . pop : { }
57
61
attrs = attrs . first if attrs . first . class == Array
58
62
59
63
attrs . each do |attr |
60
- attribute ( attr )
64
+ attribute ( attr , options )
61
65
end
62
66
end
63
67
@@ -66,6 +70,17 @@ def self.attribute(attr, options = {})
66
70
_attributes_keys [ attr ] = { key : key } if key != attr
67
71
_attributes << key unless _attributes . include? ( key )
68
72
73
+ [ :if , :unless ] . each do |switch |
74
+ next unless options . key? ( switch )
75
+ condition = { switch => options [ switch ] }
76
+
77
+ if _attributes_conditions [ condition ]
78
+ _attributes_conditions [ condition ] << key
79
+ else
80
+ _attributes_conditions [ condition ] = [ key ]
81
+ end
82
+ end
83
+
69
84
ActiveModelSerializers . silence_warnings do
70
85
define_method key do
71
86
object . read_attribute_for_serialization ( attr )
@@ -160,7 +175,7 @@ def json_key
160
175
end
161
176
162
177
def attributes
163
- attributes = self . class . _attributes . dup
178
+ attributes = self . class . _attributes . dup - useless_attributes_keys
164
179
165
180
attributes . each_with_object ( { } ) do |name , hash |
166
181
if self . class . _fragmented
@@ -171,8 +186,31 @@ def attributes
171
186
end
172
187
end
173
188
189
+ def useless_attributes_keys
190
+ self . class
191
+ . _attributes_conditions
192
+ . dup
193
+ . each_with_object ( [ ] ) do |( switch_hash , keys ) , useless_keys |
194
+ case switch_hash . keys
195
+ when [ :if ]
196
+ useless_keys << keys unless judge_attribute ( switch_hash [ :if ] )
197
+ when [ :unless ]
198
+ useless_keys << keys if judge_attribute ( switch_hash [ :unless ] )
199
+ else
200
+ useless_keys
201
+ end
202
+ end . flatten
203
+ end
204
+
174
205
protected
175
206
176
207
attr_accessor :instance_options
208
+
209
+ private
210
+
211
+ def judge_attribute ( condition )
212
+ ( condition . is_a? ( Symbol ) && send ( condition ) ) ||
213
+ ( condition . respond_to? ( :call ) && condition . call )
214
+ end
177
215
end
178
216
end
0 commit comments