Sha256: 8f36a5ced7b4252f376a7a754747a8276f7e17a36a0e2850982104f927a5101a

Contents?: true

Size: 1.41 KB

Versions: 47

Compression:

Stored size: 1.41 KB

Contents

module Krikri::MappingDSL
  ##
  # Specifies a mapping between a property name and its mapped value(s).
  # Deals with static properties (given a specific value or values), and
  # dynamic properties (where values are modified by a block).
  class PropertyDeclaration
    attr_reader :name, :value

    def initialize(name, value, _opts = {}, &block)
      if block_given?
        raise 'Block must have arity of 1 to be applied to property' unless
          block.arity == 1
        @block = block
      end
      @name = name
      @value = value
    end

    ##
    # Returns a proc that can be run to add values for the property to
    # Passes value(s) through a block, if given.
    #
    # If value is a callable object (e.g. a Proc), calls it with the
    # OriginalRecord as an argument to determine the value.
    #
    # @return [Proc] a proc that can be used to generate a value for the named
    # property.
    def to_proc
      block = @block if @block
      value = @value
      lambda do |target, record|
        value = value.call(record) if value.respond_to? :call
        return target.send(setter, value) unless block
        if value.is_a? Enumerable
          values = value.map { |v| instance_exec(v, &block) }
          target.send(setter, values)
        else
          target.send(setter, instance_exec(value, &block))
        end
      end
    end

    private

    def setter
      "#{@name}=".to_sym
    end
  end
end

Version data entries

47 entries across 47 versions & 1 rubygems

Version Path
krikri-0.12.4 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.12.3 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.12.1 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.12.0 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.12.0.pre.rc.1 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.11.2 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.11.1 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.11.0 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.10.1 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.10.0 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.9.0 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.8.9 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.8.8 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.8.7 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.8.6 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.8.5 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.8.4 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.8.3 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.8.2 lib/krikri/mapping_dsl/property_declaration.rb
krikri-0.8.1 lib/krikri/mapping_dsl/property_declaration.rb