Sha256: ae81647c1b0dc90a954a554b8f6ff7240e234570b99c65d9b2ad9670b25c516f

Contents?: true

Size: 576 Bytes

Versions: 1

Compression:

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

1 entries across 1 versions & 1 rubygems

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