Sha256: b40fd8c6670ee7cc3750f92e9bbca3353ff9fdb19b40b59268e898c35ea6a9d7

Contents?: true

Size: 594 Bytes

Versions: 1

Compression:

Stored size: 594 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.__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

1 entries across 1 versions & 1 rubygems

Version Path
alba-0.2.0 lib/alba/many.rb