Sha256: f4399d60c6f3870bd3371e6293cce7255d5b6616c501ef1aa862b27fac56fb84

Contents?: true

Size: 579 Bytes

Versions: 6

Compression:

Stored size: 579 Bytes

Contents

module Alba
  # Representing one association
  class One
    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)
      object = target.public_send(@name)
      @resource ||= resource_class
      @resource.new(object).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/one.rb
alba-0.7.0 lib/alba/one.rb
alba-0.6.0 lib/alba/one.rb
alba-0.5.0 lib/alba/one.rb
alba-0.4.0 lib/alba/one.rb
alba-0.3.0 lib/alba/one.rb