Class: FunctionalHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/functional_hash.rb,
lib/functional_hash/version.rb

Constant Summary collapse

VERSION =
"0.3.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.disable!Object



30
31
32
33
34
# File 'lib/functional_hash.rb', line 30

def self.disable!
  if Hash.instance_methods.include? :fn
    Hash.class_eval { undef_method :fn }
  end
end

.enable!Object



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/functional_hash.rb', line 16

def self.enable!
  unless Hash.respond_to? :fn
    Hash.class_eval do
      def fn
        FunctionalHash.new.tap do |fh|
          self.each do |key, val|
            fh[key] = val
          end
        end
      end
    end
  end
end

.from_hash(hash) ⇒ Object

Raises:

  • (ArgumentError)


36
37
38
39
40
41
# File 'lib/functional_hash.rb', line 36

def self.from_hash(hash)
  raise ArgumentError, 'FunctionalHash.from_hash requires a Hash' unless hash.is_a? Hash
  new.tap do |fn_hash|
    hash.each { |k, v| fn_hash[k.dup] = v.dup }
  end
end

Instance Method Details

#[](*args) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/functional_hash.rb', line 2

def [](*args)
  key = args.shift
  if fetch(key, nil).is_a? Proc
    if fetch(key).arity == 0
      fetch(key).call
    else
      args.unshift(self)
      fetch(key).call(*args)
    end
  else
    super(key)
  end
end