Module: MagicHash

Defined in:
lib/magic_hash.rb

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &blk) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/magic_hash.rb', line 30

def method_missing(method_name, *args, &blk)
  message = method_name.to_s.strip.gsub(/-/,"_")
  if message =~ /=/
    self[message.gsub(/=/,"").to_sym]= args.flatten.first
    self.objectify
    return
  elsif message =~ /\?/
    return !!(self[message.gsub(/\?/,"").to_sym])
  else
    result = self[message.to_sym]
    return result if result
  end

  super(method_name, *args, &blk)
end

Class Method Details

.newObject



3
4
5
# File 'lib/magic_hash.rb', line 3

def self.new
  Hash.new.extend(MagicHash)
end

Instance Method Details

#objectifyObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/magic_hash.rb', line 7

def objectify
  tmp = MagicHash.new
  self.each_pair do |key, value|
    new_key = key.is_a?(Symbol) ? key : key.gsub(/\s|-/,"_").strip.to_sym
    if(value.is_a? Hash)
      value.extend(MagicHash) unless value.respond_to? :objectify
      tmp[new_key] = value.objectify
    elsif(value.is_a? Array)
      tmp[new_key] = value.map do |val|
        if val.is_a?(Hash)
          val.extend(MagicHash) unless val.respond_to? :objectify
          val.objectify
        else
          val
        end
      end
    else
      tmp[new_key] = value
    end
  end
  self.replace(tmp)
end