mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
Add auto-stripping of question mark for attributes
This commit is contained in:
parent
40d53aaa16
commit
bded293529
@ -79,10 +79,12 @@ end
|
||||
end
|
||||
|
||||
def attributes(*attrs)
|
||||
@_attributes.concat attrs
|
||||
|
||||
attrs.each do |attr|
|
||||
define_method attr do
|
||||
striped_attr = strip_attribute attr
|
||||
|
||||
@_attributes << striped_attr
|
||||
|
||||
define_method striped_attr do
|
||||
object.read_attribute_for_serialization attr
|
||||
end unless method_defined?(attr)
|
||||
end
|
||||
@ -98,6 +100,14 @@ end
|
||||
|
||||
private
|
||||
|
||||
def strip_attribute(attr)
|
||||
symbolized = attr.is_a?(Symbol)
|
||||
|
||||
attr = attr.to_s.gsub(/\?\Z/, '')
|
||||
attr = attr.to_sym if symbolized
|
||||
attr
|
||||
end
|
||||
|
||||
def build_serializer_class(resource, options)
|
||||
"".tap do |klass_name|
|
||||
klass_name << "#{options[:namespace]}::" if options[:namespace]
|
||||
|
||||
4
test/fixtures/poro.rb
vendored
4
test/fixtures/poro.rb
vendored
@ -1,11 +1,13 @@
|
||||
class Model
|
||||
def initialize(hash={})
|
||||
def initialize(hash = {})
|
||||
@attributes = hash
|
||||
end
|
||||
|
||||
def read_attribute_for_serialization(name)
|
||||
if name == :id || name == 'id'
|
||||
object_id
|
||||
elsif respond_to?(name)
|
||||
send name
|
||||
else
|
||||
@attributes[name]
|
||||
end
|
||||
|
||||
@ -36,6 +36,22 @@ module ActiveModel
|
||||
assert_equal([:name, :description],
|
||||
another_inherited_serializer_klass._attributes)
|
||||
end
|
||||
|
||||
def tests_query_attributes_strip_question_mark
|
||||
model = Class.new(::Model) do
|
||||
def strip?
|
||||
true
|
||||
end
|
||||
end
|
||||
|
||||
serializer = Class.new(ActiveModel::Serializer) do
|
||||
attributes :strip?
|
||||
end
|
||||
|
||||
actual = serializer.new(model.new).as_json
|
||||
|
||||
assert_equal({ strip: true }, actual)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Loading…
Reference in New Issue
Block a user