Class: BlockIsHash

Inherits:
Object
  • Object
show all
Defined in:
lib/block-is-hash/class.rb

Instance Method Summary collapse

Constructor Details

#initialize(repeats, &block) ⇒ BlockIsHash

Returns a new instance of BlockIsHash.



2
3
4
5
6
# File 'lib/block-is-hash/class.rb', line 2

def initialize repeats, &block
  @repeats = repeats
  @hash = {}
  instance_eval(&block)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/block-is-hash/class.rb', line 8

def method_missing name, *args, &block
  if block
    args.push BlockIsHash.new(@repeats, &block).to_hash
  end

  value = args.length == 1 ? args[0] : args

  if @repeats.include? name and @hash.include? name
    @hash[name].push value
  elsif @repeats.include? name
    @hash[name] = [value]
  elsif @hash.include? name
    raise "#{name} entry is declared twice."
  else
    @hash[name] = value
  end
end

Instance Method Details

#to_hashObject



26
27
28
# File 'lib/block-is-hash/class.rb', line 26

def to_hash
  @hash
end