Sha256: e3d4c49e711cb7d2140eb955c009967a544e1a0011af292d2001225378bd4f1f

Contents?: true

Size: 1.57 KB

Versions: 6

Compression:

Stored size: 1.57 KB

Contents

# = hashbuilder.rb
#
# == Copyright (c) 2006 Thomas Sawyer
#
#   Ruby License
#
#   This module is free software. You may use, modify, and/or redistribute this
#   software under the same terms as Ruby.
#
#   This program is distributed in the hope that it will be useful, but WITHOUT
#   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
#   FOR A PARTICULAR PURPOSE.
#
# == Author(s)
#
# * Thomas Sawyer

# Author::    Thomas Sawyer
# Copyright:: Copyright (c) 2006 Thomas Sawyer
# License::   Ruby License

require 'facets/more/basicobject.rb'

# = Hash Builder
#
# Build a hash programmatically.
#
# Build a hash from missing method calls.

class HashBuilder < BasicObject

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

  def initialize( blockstr=nil, &block )
    @hash = {}
    @flag = {}
  end

  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

  def to_h ; @hash ; end

  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

end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
facets-1.4.2 lib/facets/more/hashbuilder.rb
facets-1.4.0 lib/facets/more/hashbuilder.rb
facets-1.4.1 lib/facets/more/hashbuilder.rb
facets-1.4.3 lib/facets/more/hashbuilder.rb
facets-1.4.5 lib/facets/more/hashbuilder.rb
facets-1.4.4 lib/facets/more/hashbuilder.rb