Add auto-stripping of question mark for attributes

This commit is contained in:
Andrey Krivko 2014-09-26 15:42:41 +07:00
parent 40d53aaa16
commit bded293529
3 changed files with 32 additions and 4 deletions

View File

@ -79,10 +79,12 @@ end
end end
def attributes(*attrs) def attributes(*attrs)
@_attributes.concat attrs
attrs.each do |attr| 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 object.read_attribute_for_serialization attr
end unless method_defined?(attr) end unless method_defined?(attr)
end end
@ -98,6 +100,14 @@ end
private 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) def build_serializer_class(resource, options)
"".tap do |klass_name| "".tap do |klass_name|
klass_name << "#{options[:namespace]}::" if options[:namespace] klass_name << "#{options[:namespace]}::" if options[:namespace]

View File

@ -1,11 +1,13 @@
class Model class Model
def initialize(hash={}) def initialize(hash = {})
@attributes = hash @attributes = hash
end end
def read_attribute_for_serialization(name) def read_attribute_for_serialization(name)
if name == :id || name == 'id' if name == :id || name == 'id'
object_id object_id
elsif respond_to?(name)
send name
else else
@attributes[name] @attributes[name]
end end

View File

@ -36,6 +36,22 @@ module ActiveModel
assert_equal([:name, :description], assert_equal([:name, :description],
another_inherited_serializer_klass._attributes) another_inherited_serializer_klass._attributes)
end 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 end
end end