Class: HashMapper::Dsl

Inherits:
Object
  • Object
show all
Defined in:
lib/hash-mapper/dsl.rb

Defined Under Namespace

Classes: Key

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Dsl

Returns a new instance of Dsl.



9
10
11
12
# File 'lib/hash-mapper/dsl.rb', line 9

def initialize(&block)
  @keys = []
  evaluate(&block) if block_given?
end

Instance Attribute Details

#keysObject (readonly)

Returns the value of attribute keys.



7
8
9
# File 'lib/hash-mapper/dsl.rb', line 7

def keys
  @keys
end

Instance Method Details

#each_keyObject



14
15
16
# File 'lib/hash-mapper/dsl.rb', line 14

def each_key
  @keys.each { |k| yield(k) }
end

#evaluate(&block) ⇒ Object



18
19
20
21
22
23
24
25
26
27
# File 'lib/hash-mapper/dsl.rb', line 18

def evaluate(&block)
  case block.arity
  when 0
    Combinder.new(self, block.binding).instance_eval(&block)
  when 1
    yield self
  else
    raise "Too many args for block"
  end
end

#key(name, *opts) ⇒ Object

opts -

source - Symbol | [Symbol]
create - Symbol
allow_nil - Symbol

Raises:

  • (ArgumentError)


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/hash-mapper/dsl.rb', line 65

def key(name, *opts)
  hash_opts = opts.select { |v| v.kind_of?(Hash) }.inject(&:merge) || {}
  source = hash_opts[:source]
  then_block = hash_opts[:then]
  value = hash_opts[:eq]
  if_key = hash_opts.fetch(:if_key) { [] }
  create = opts.empty? || opts.include?(:create) || opts.include?(:allow_nil)
  allow_nil = opts.include?(:allow_nil)

  # TODO: validate the option keys.

  # Normalize source
  source =  case source
            when Array
              source
            when Symbol
              [source]
            else
              # Use the key as value source when source is missing
              [name]
            end

  # Normalize if_key
  if_key =  case if_key
            when Array
              if_key
            when Symbol
              [if_key]
            end

  # -- Sanity check
  raise ArgumentError.new("A :then block is required if a key has multiple sources.") if source.size > 1 && !then_block

  @keys.push Key.new(
    name: name,
    source: source,
    create: create,
    allow_nil: allow_nil,
    then_block: then_block,
    if_key: if_key,
    value: value
  )
end

#merge(*opts, &block) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/hash-mapper/dsl.rb', line 44

def merge(*opts, &block)
  hash_opts = opts.select { |v| v.kind_of?(Hash) }.inject(&:merge) || {}
  source = hash_opts.fetch(:source) { [] }
  then_block = block || hash_opts[:then]

  # Normalize source
  source =  case source
            when Array
              source
            when Symbol
              [source]
            end

  @keys.push Key.new(merge: true, then_block: then_block, source: source)
end