class ActiveHashFields::HashAsObject

Attributes

hash[R]

Public Class Methods

new(hash, defaults={}) click to toggle source
# 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

Public Instance Methods

convert_to_correct_type(k,v) click to toggle source
# 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
method_missing(name, *args, &blk) click to toggle source
# 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