Class: ActiveHashFields::HashAsObject
- Inherits:
-
Object
- Object
- ActiveHashFields::HashAsObject
- Defined in:
- lib/active_hash_fields.rb
Instance Attribute Summary collapse
-
#hash ⇒ Object
readonly
Returns the value of attribute hash.
Instance Method Summary collapse
- #convert_to_correct_type(k, v) ⇒ Object
-
#initialize(hash, defaults = {}) ⇒ HashAsObject
constructor
A new instance of HashAsObject.
- #method_missing(name, *args, &blk) ⇒ Object
Constructor Details
#initialize(hash, defaults = {}) ⇒ HashAsObject
Returns a new instance of HashAsObject.
7 8 9 10 11 12 13 14 |
# File 'lib/active_hash_fields.rb', line 7 def initialize(hash, defaults={}) hash ||= {} defaults.stringify_keys!; hash.stringify_keys! @defaults = defaults @hash = defaults.merge(hash) @hash.each { |k,v| @hash[k] = convert_to_correct_type(k,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
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/active_hash_fields.rb', line 16 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] = convert_to_correct_type(k, args[0]) end end else return @hash.send(name, *args, &blk) end nil end |
Instance Attribute Details
#hash ⇒ Object (readonly)
Returns the value of attribute hash.
5 6 7 |
# File 'lib/active_hash_fields.rb', line 5 def hash @hash end |
Instance Method Details
#convert_to_correct_type(k, v) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/active_hash_fields.rb', line 33 def convert_to_correct_type(k,v) if @defaults[k] == false || @defaults[k] == true if (v == "1" || v == "true" || v == true) true elsif v == "0" || v == "false" || v == false false end elsif @defaults[k].kind_of?(Numeric) if @defaults[k] =~ /\./ v.to_f else v.to_i end else v end end |