class HashBuilder

HashBuilder

Build a hash programmatically via a fluent DSL-like syntax. In other words, this uses method_missing to buld the hash.

Public Class Methods

load( blockstr, &block ) click to toggle source
# File lib/more/facets/hashbuilder.rb, line 47
def self.load( blockstr, &block )
  new( blockstr, &block ).to_h
end
new( blockstr=nil, &block ) click to toggle source

def self.build( blockstr=nil, &block )

self.new.build( blockstr, &block ).to_h

end

# File lib/more/facets/hashbuilder.rb, line 55
def initialize( blockstr=nil, &block )
  @hash = {}
  @flag = {}
  build!( blockstr, &block )
end

Public Instance Methods

build!( blockstr=nil, &block ) click to toggle source
# File lib/more/facets/hashbuilder.rb, line 61
def build!( blockstr=nil, &block )
  raise "both string and block given" if blockstr and block_given?
  if blockstr
    instance_eval blockstr
  else
    instance_eval &block
  end
  self  # or to_h ?
end
method_missing( sym, *args, &block ) click to toggle source
# File lib/more/facets/hashbuilder.rb, line 73
def method_missing( sym, *args, &block )
  sym = sym.to_s.downcase.chomp('=')

  if @hash.key?(sym)
    unless @flag[sym]
      @hash[sym] = [ @hash[sym] ]
      @flag[sym] = true
    end
    if block_given?
      @hash[sym] << self.__class__.new( &block ).to_h
    else
      @hash[sym] << args[0]
    end
  else
    if block_given?
      @hash[sym] = self.__class__.new( &block ).to_h
    else
      @hash[sym] = args[0]
    end
  end

end
to_h() click to toggle source
# File lib/more/facets/hashbuilder.rb, line 71
def to_h ; @hash ; end