Sha256: 9302c15307d5437cdcb58d6a05cd99c1a6d23df8f41420bfaff23cd161cc677b

Contents?: true

Size: 597 Bytes

Versions: 6

Compression:

Stored size: 597 Bytes

Contents

module Alba
  # Representing many association
  class Many
    def initialize(name:, resource: nil, &block)
      @name = name
      @resource = resource
      @block = block
      raise ArgumentError, 'resource or block is required' if @resource.nil? && @block.nil?
    end

    def to_hash(target)
      objects = target.public_send(@name)
      @resource ||= resource_class
      objects.map { |o| @resource.new(o).to_hash }
    end

    private

    def resource_class
      klass = Class.new
      klass.include(::Alba::Resource)
      klass.class_exec(&@block)
      klass
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
alba-0.8.0 lib/alba/many.rb
alba-0.7.0 lib/alba/many.rb
alba-0.6.0 lib/alba/many.rb
alba-0.5.0 lib/alba/many.rb
alba-0.4.0 lib/alba/many.rb
alba-0.3.0 lib/alba/many.rb