Module: Hashoid

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

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"0.0.1"

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



95
96
97
# File 'lib/hashoid.rb', line 95

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

#eachObject



85
86
87
88
89
90
91
92
93
# File 'lib/hashoid.rb', line 85

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



72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/hashoid.rb', line 72

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 defined?(field).nil? # check if it's included as a reader attribute
      result = v.instance_of?(Array) ? init_objects(field, v) : init_object(field, v)
      instance_variable_set("@#{field}", result) if result
    end
  end
end

#to_hObject



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

def to_h
  @args
end

#to_jsonObject



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

def to_json
  to_h.to_json
end