Add inline syntax for defining associations

Adapted from
https://github.com/rails-api/active_model_serializers/pull/1262
This commit is contained in:
Lucas Hosseini 2015-10-20 00:54:56 +02:00 committed by Benjamin Fleischer
parent 6020450fe4
commit 7cbef1b3b5
2 changed files with 18 additions and 13 deletions

View File

@ -69,7 +69,7 @@ module ActiveModel
serializer.class_attribute :_cache_digest # @api private : Generated
end
# Serializers inherit serialized_attributes and _attributes_keys.
# Serializers inherit serialized_attributes, _attributes_keys, and _reflections.
# Generates a unique digest for each serializer at load.
def self.inherited(base)
caller_line = caller.first

View File

@ -13,9 +13,8 @@ module ActiveModel
DEFAULT_INCLUDE_TREE = ActiveModel::Serializer::IncludeTree.from_string('*')
included do |base|
class << base
attr_accessor :_reflections
end
base.class_attribute :_reflections
base._reflections ||= []
extend ActiveSupport::Autoload
autoload :Association
@ -28,8 +27,10 @@ module ActiveModel
end
module ClassMethods
# Serializers inherit _reflections.
def inherited(base)
base._reflections = self._reflections.try(:dup) || []
super
base._reflections = _reflections.dup
end
# @param [Symbol] name of the association
@ -39,8 +40,8 @@ module ActiveModel
# @example
# has_many :comments, serializer: CommentSummarySerializer
#
def has_many(name, options = {})
associate HasManyReflection.new(name, options)
def has_many(name, options = {}, &block)
associate(HasManyReflection.new(name, options), block)
end
# @param [Symbol] name of the association
@ -50,8 +51,8 @@ module ActiveModel
# @example
# belongs_to :author, serializer: AuthorSerializer
#
def belongs_to(name, options = {})
associate BelongsToReflection.new(name, options)
def belongs_to(name, options = {}, &block)
associate(BelongsToReflection.new(name, options), block)
end
# @param [Symbol] name of the association
@ -61,8 +62,8 @@ module ActiveModel
# @example
# has_one :author, serializer: AuthorSerializer
#
def has_one(name, options = {})
associate HasOneReflection.new(name, options)
def has_one(name, options = {}, &block)
associate(HasOneReflection.new(name, options), block)
end
private
@ -73,11 +74,15 @@ module ActiveModel
#
# @api private
#
def associate(reflection)
def associate(reflection, block)
self._reflections = _reflections.dup
define_method reflection.name do
if block_given?
instance_eval(&block)
else
object.send reflection.name
end
end unless method_defined?(reflection.name)
self._reflections << reflection