Merge pull request #1031 from bolshakov/feature/disaplow_to_define_multiple_associations_at_once

Disallow to define multiple associations at once
This commit is contained in:
João Moura 2015-08-01 18:22:00 -03:00
commit c4af610ed2

View File

@ -29,65 +29,57 @@ module ActiveModel
base._reflections = self._reflections.try(:dup) || [] base._reflections = self._reflections.try(:dup) || []
end end
# @param [Array(Array<Symbol>, Hash{Symbol => Object})] attrs # @param [Symbol] name of the association
# @param [Hash<Symbol => any>] options for the reflection
# @return [void] # @return [void]
# #
# @example # @example
# has_many :comments, serializer: CommentSummarySerializer # has_many :comments, serializer: CommentSummarySerializer
# has_many :commits, authors
# #
def has_many(*attrs) def has_many(name, options = {})
associate attrs do |name, options| associate HasManyReflection.new(name, options)
HasManyReflection.new(name, options)
end
end end
# @param [Array(Array<Symbol>, Hash{Symbol => Object})] attrs # @param [Symbol] name of the association
# @param [Hash<Symbol => any>] options for the reflection
# @return [void] # @return [void]
# #
# @example # @example
# belongs_to :author, serializer: AuthorSerializer # belongs_to :author, serializer: AuthorSerializer
# #
def belongs_to(*attrs) def belongs_to(name, options = {})
associate attrs do |name, options| associate BelongsToReflection.new(name, options)
BelongsToReflection.new(name, options)
end
end end
# @param [Array(Array<Symbol>, Hash{Symbol => Object})] attrs # @param [Symbol] name of the association
# @param [Hash<Symbol => any>] options for the reflection
# @return [void] # @return [void]
# #
# @example # @example
# has_one :author, serializer: AuthorSerializer # has_one :author, serializer: AuthorSerializer
# #
def has_one(*attrs) def has_one(name, options = {})
associate attrs do |name, options| associate HasOneReflection.new(name, options)
HasOneReflection.new(name, options)
end
end end
private private
# Add reflection and define {name} accessor. # Add reflection and define {name} accessor.
# @param [Array<Symbol>] # @param [ActiveModel::Serializer::Reflection] reflection
# @yield [Symbol] return reflection # @return [void]
# #
# @api private # @api private
# #
def associate(attrs) def associate(reflection)
options = attrs.extract_options!
self._reflections = _reflections.dup self._reflections = _reflections.dup
attrs.each do |name| unless method_defined?(reflection.name)
unless method_defined?(name) define_method reflection.name do
define_method name do object.send reflection.name
object.send name
end
end end
self._reflections << yield(name, options)
end end
self._reflections << reflection
end end
end end