Class: ActiveHashFields::HashAsObject

Inherits:
Object
  • Object
show all
Defined in:
lib/active_hash_fields.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash, defaults = {}) ⇒ HashAsObject

Returns a new instance of HashAsObject.



7
8
9
10
11
12
13
# File 'lib/active_hash_fields.rb', line 7

def initialize(hash, defaults={})
  hash ||= {}
  defaults.stringify_keys!; hash.stringify_keys!
  @hash = defaults.merge(hash)
  @hash.each { |k,v| @hash[k] = self.class.convert_to_boolean(v) }
  @hash.delete_if { |k,v| defaults[k].nil? }
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



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

def method_missing(name, *args, &blk)
  name = name.to_s
  if @hash
    if @hash.has_key?(name)
      return @hash[name]
    elsif name.match(/=$/)
      k = name.sub(/=$/, "")
      if @hash.has_key?(k)
        @hash[k] = self.class.convert_to_boolean(args[0])
      end
    end
  else
    return @hash.send(name, *args, &blk)
  end
  nil
end

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash.



5
6
7
# File 'lib/active_hash_fields.rb', line 5

def hash
  @hash
end

Class Method Details

.convert_to_boolean(v) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/active_hash_fields.rb', line 32

def self.convert_to_boolean(v)
  if (v == "1" || v == "true" || v == true)
    true
  elsif v == "0" || v == "false" || v == false
    false
  else
    v
  end
end