From ebf97c9bd1ec9e1a7310ac2b294aa09de4bd8dda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Wed, 26 Feb 2020 17:06:30 -0500 Subject: [PATCH] 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. --- lib/active_model/serializer.rb | 12 ++++++++---- test/fixtures/poro.rb | 8 ++++---- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index a89a79a8..884564a8 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -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 diff --git a/test/fixtures/poro.rb b/test/fixtures/poro.rb index d122f097..73bc53b0 100644 --- a/test/fixtures/poro.rb +++ b/test/fixtures/poro.rb @@ -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