lib/alba/association.rb in alba-2.4.1 vs lib/alba/association.rb in alba-2.4.2
- old
+ new
@@ -6,11 +6,11 @@
class << self
# cache for `const_get`
attr_reader :const_cache
end
- attr_reader :object, :name
+ attr_reader :name
# @param name [Symbol, String] name of the method to fetch association
# @param condition [Proc, nil] a proc filtering data
# @param resource [Class<Alba::Resource>, nil] a resource class for the association
# @param params [Hash] params override for the association
@@ -34,30 +34,31 @@
# @param within [Hash] determines what associations to be serialized. If not set, it serializes all associations.
# @param params [Hash] user-given Hash for arbitrary data
# @return [Hash]
def to_h(target, within: nil, params: {})
params = params.merge(@params)
- @object = target.__send__(@name)
- @object = @condition.call(object, params, target) if @condition
- return if @object.nil?
+ object = target.__send__(@name)
+ object = @condition.call(object, params, target) if @condition
+ return if object.nil?
if @resource.is_a?(Proc)
- return to_h_with_each_resource(within, params) if @object.is_a?(Enumerable)
+ return to_h_with_each_resource(object, within, params) if object.is_a?(Enumerable)
- @resource.call(@object).new(@object, within: within, params: params).to_h
+ @resource.call(object).new(object, within: within, params: params).to_h
else
- to_h_with_constantize_resource(within, params)
+ to_h_with_constantize_resource(object, within, params)
end
end
private
def constantize(resource)
case resource # rubocop:disable Style/MissingElse
when Class
resource
when Symbol, String
+ Object.const_get(resource)
self.class.const_cache.fetch(resource) do
self.class.const_cache[resource] = Object.const_get(resource)
end
end
end
@@ -74,16 +75,16 @@
else
raise ArgumentError, 'When Alba.inflector is nil, either resource or block is required'
end
end
- def to_h_with_each_resource(within, params)
- @object.map do |item|
+ def to_h_with_each_resource(object, within, params)
+ object.map do |item|
@resource.call(item).new(item, within: within, params: params).to_h
end
end
- def to_h_with_constantize_resource(within, params)
+ def to_h_with_constantize_resource(object, within, params)
@resource = constantize(@resource)
@resource.new(object, params: params, within: within).to_h
end
end
end