lib/alba/association.rb in alba-1.6.0 vs lib/alba/association.rb in alba-2.0.0
- old
+ new
@@ -9,16 +9,20 @@
attr_reader :object, :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
# @param nesting [String] a namespace where source class is inferred with
+ # @param key_transformation [Symbol] key transformation type
# @param block [Block] used to define resource when resource arg is absent
- def initialize(name:, condition: nil, resource: nil, nesting: nil, &block)
+ def initialize(name:, condition: nil, resource: nil, params: {}, nesting: nil, key_transformation: :none, &block)
@name = name
@condition = condition
@resource = resource
+ @params = params
+ @key_transformation = key_transformation
return if @resource
assign_resource(nesting, block)
end
@@ -27,16 +31,20 @@
# @param target [Object] the object having an association method
# @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: {})
- @object = target.public_send(@name)
- @object = @condition.call(object, params) if @condition
+ params = params.merge(@params) unless @params.empty?
+ @object = target.__send__(@name)
+ @object = @condition.call(object, params, target) if @condition
return if @object.nil?
- @resource = constantize(@resource)
- @resource.new(object, params: params, within: within).to_h
+ if @resource.is_a?(Proc) && @object.is_a?(Enumerable)
+ to_h_with_each_resource(within, params)
+ else
+ to_h_with_constantize_resource(within, params)
+ end
end
private
def constantize(resource)
@@ -56,8 +64,20 @@
elsif Alba.inferring
Alba.infer_resource_class(@name, nesting: nesting)
else
raise ArgumentError, 'When Alba.inferring is false, either resource or block is required'
end
+ end
+
+ def to_h_with_each_resource(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)
+ @resource = constantize(@resource)
+ @resource.transform_keys(@key_transformation)
+ @resource.new(object, params: params, within: within).to_h
end
end
end