mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 13:56:53 +00:00
Define attribute methods in a module included in the base class
This will make possible to call `super` in method overrides and to define the methods after the `attributes` method was called without warnings.
This commit is contained in:
parent
f72ab35d9d
commit
ebf97c9bd1
@ -19,6 +19,10 @@ module ActiveModel
|
||||
base._associations = (_associations || {}).dup
|
||||
end
|
||||
|
||||
def generated_modules
|
||||
@generated_attribute_methods ||= Module.new.tap { |mod| include mod }
|
||||
end
|
||||
|
||||
def setup
|
||||
@mutex.synchronize do
|
||||
yield CONFIG
|
||||
@ -90,9 +94,9 @@ end
|
||||
|
||||
@_attributes << striped_attr
|
||||
|
||||
define_method striped_attr do
|
||||
generated_modules.define_method striped_attr do
|
||||
object.read_attribute_for_serialization attr
|
||||
end unless method_defined?(attr)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@ -130,9 +134,9 @@ end
|
||||
options = attrs.extract_options!
|
||||
|
||||
attrs.each do |attr|
|
||||
define_method attr do
|
||||
generated_modules.define_method attr do
|
||||
object.send attr
|
||||
end unless method_defined?(attr)
|
||||
end
|
||||
|
||||
@_associations[attr] = klass.new(attr, options)
|
||||
end
|
||||
|
||||
8
test/fixtures/poro.rb
vendored
8
test/fixtures/poro.rb
vendored
@ -128,12 +128,12 @@ class UserInfoSerializer < ActiveModel::Serializer
|
||||
end
|
||||
|
||||
class ProfileSerializer < ActiveModel::Serializer
|
||||
attributes :name, :description
|
||||
|
||||
def description
|
||||
description = object.read_attribute_for_serialization(:description)
|
||||
description = super
|
||||
scope ? "#{description} - #{scope}" : description
|
||||
end
|
||||
|
||||
attributes :name, :description
|
||||
end
|
||||
|
||||
class CategorySerializer < ActiveModel::Serializer
|
||||
@ -147,7 +147,7 @@ class PostSerializer < ActiveModel::Serializer
|
||||
|
||||
def title
|
||||
keyword = serialization_options[:highlight_keyword]
|
||||
title = object.read_attribute_for_serialization(:title)
|
||||
title = super
|
||||
title = title.gsub(keyword,"'#{keyword}'") if keyword
|
||||
title
|
||||
end
|
||||
|
||||
Loading…
Reference in New Issue
Block a user