Module: Hashoid

Defined in:
lib/hashoid.rb,
lib/hashoid/version.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"0.0.3"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



6
7
8
# File 'lib/hashoid.rb', line 6

def self.included base
  base.extend(ClassMethods)
end

Instance Method Details

#[](field) ⇒ Object



100
101
102
# File 'lib/hashoid.rb', line 100

def [] field
  respond_to?(field) ? self.send(field) : @args[field]
end

#eachObject



90
91
92
93
94
95
96
97
98
# File 'lib/hashoid.rb', line 90

def each
  self.class.field_names.map do |f| 
    [f, self.send(f)]
  end.reject do |_, v| 
    v.nil?
  end.each do |f, v| 
    yield(f, v)
  end 
end

#initialize(args = {}) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/hashoid.rb', line 76

def initialize args={}
  self.class._fields.each {|k, _| instance_variable_set("@#{k}", self.class.field_default(k))}

  @args = args
  args.each do |k, v|
    field = k.to_s.gsub('-', '_').to_sym
    unless self.class._fields[field].nil? # check if it's a declared field
      result = v.instance_of?(Array) ? init_objects(field, v) : init_object(field, v)
      instance_variable_set("@#{field}", result)
      self.class.alias_boolean(field) if !!result == result # convenience field? method for boolean values
    end
  end
end

#to_hObject



104
105
106
# File 'lib/hashoid.rb', line 104

def to_h
  @args
end

#to_jsonObject



108
109
110
# File 'lib/hashoid.rb', line 108

def to_json
  to_h.to_json
end