Build a hash programmatically via a fluent DSL-like syntax. In other words, this uses method_missing to buld the hash.
# File lib/more/facets/hashbuilder.rb, line 47 def self.load( blockstr, &block ) new( blockstr, &block ).to_h end
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
# 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
# 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
# File lib/more/facets/hashbuilder.rb, line 71 def to_h ; @hash ; end