Skip to content

Commit afa0361

Browse files
committed
Dynamic attribute filtering on serializers
Add a method named filter that by default returns all fields. Actual serialised implementations can override this method to dynamically filter the list of attributes to be serialized. Implements rails-api#1058.
1 parent b594d14 commit afa0361

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

lib/active_model/serializer.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,10 @@ def json_key
125125
@root || object.class.model_name.to_s.underscore
126126
end
127127

128+
def fields(keys)
129+
keys
130+
end
131+
128132
def attributes(options = {})
129133
attributes =
130134
if options[:fields]
@@ -133,7 +137,7 @@ def attributes(options = {})
133137
self.class._attributes.dup
134138
end
135139

136-
attributes.each_with_object({}) do |name, hash|
140+
fields(attributes).each_with_object({}) do |name, hash|
137141
unless self.class._fragmented
138142
hash[name] = send(name)
139143
else

test/serializers/attributes_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,24 @@ def test_attributes_definition
1818
@profile_serializer.class._attributes)
1919
end
2020

21+
def test_attributes
22+
assert_equal({ name: 'Name 1', description: 'Description 1' },
23+
@profile_serializer.attributes)
24+
end
25+
2126
def test_attributes_with_fields_option
2227
assert_equal({ name: 'Name 1' },
2328
@profile_serializer.attributes(fields: [:name]))
2429
end
2530

31+
def test_attributes_with_fields_method
32+
@profile_serializer.define_singleton_method(:fields) do |keys|
33+
keys - [:name]
34+
end
35+
assert_equal({ description: 'Description 1' },
36+
@profile_serializer.attributes)
37+
end
38+
2639
def test_attributes_inheritance_definition
2740
assert_equal([:id, :body], @serializer_klass._attributes)
2841
end

0 commit comments

Comments
 (0)