Skip to content

Commit 06e3bb7

Browse files
committed
Merge pull request #662 from jastkand/remove-question-sign
Add auto-stripping of question mark for attributes
2 parents e41eedd + bded293 commit 06e3bb7

File tree

3 files changed

+32
-4
lines changed

3 files changed

+32
-4
lines changed

lib/active_model/serializer.rb

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,10 +79,12 @@ def root_name
7979
end
8080

8181
def attributes(*attrs)
82-
@_attributes.concat attrs
83-
8482
attrs.each do |attr|
85-
define_method attr do
83+
striped_attr = strip_attribute attr
84+
85+
@_attributes << striped_attr
86+
87+
define_method striped_attr do
8688
object.read_attribute_for_serialization attr
8789
end unless method_defined?(attr)
8890
end
@@ -98,6 +100,14 @@ def has_many(*attrs)
98100

99101
private
100102

103+
def strip_attribute(attr)
104+
symbolized = attr.is_a?(Symbol)
105+
106+
attr = attr.to_s.gsub(/\?\Z/, '')
107+
attr = attr.to_sym if symbolized
108+
attr
109+
end
110+
101111
def build_serializer_class(resource, options)
102112
"".tap do |klass_name|
103113
klass_name << "#{options[:namespace]}::" if options[:namespace]

test/fixtures/poro.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
class Model
2-
def initialize(hash={})
2+
def initialize(hash = {})
33
@attributes = hash
44
end
55

66
def read_attribute_for_serialization(name)
77
if name == :id || name == 'id'
88
object_id
9+
elsif respond_to?(name)
10+
send name
911
else
1012
@attributes[name]
1113
end

test/unit/active_model/serializer/attributes_test.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,22 @@ def test_attributes_inheritance
3636
assert_equal([:name, :description],
3737
another_inherited_serializer_klass._attributes)
3838
end
39+
40+
def tests_query_attributes_strip_question_mark
41+
model = Class.new(::Model) do
42+
def strip?
43+
true
44+
end
45+
end
46+
47+
serializer = Class.new(ActiveModel::Serializer) do
48+
attributes :strip?
49+
end
50+
51+
actual = serializer.new(model.new).as_json
52+
53+
assert_equal({ strip: true }, actual)
54+
end
3955
end
4056
end
4157
end

0 commit comments

Comments
 (0)