Class: KondutoBase

Inherits:
Object
  • Object
show all
Extended by:
Konduto::Associations, Konduto::Attributes
Includes:
Konduto::Validations
Defined in:
lib/konduto-ruby/konduto_base.rb

Instance Method Summary collapse

Methods included from Konduto::Associations

has_many, has_one

Methods included from Konduto::Attributes

attributes

Methods included from Konduto::Validations

included, #valid?

Constructor Details

#initialize(*args) ⇒ KondutoBase

Returns a new instance of KondutoBase.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/konduto-ruby/konduto_base.rb', line 10

def initialize(*args)
  unless args[0].nil?
    args[0].each do |key, value|
      unless value.nil?
        if respond_to? "#{key}=".to_sym
          send("#{key}=", value)
        elsif key == 'class'
          send('klass=', value)
        else
          instance_variable_set("@#{key}", value)
        end
      end
    end
  end
end

Instance Method Details

#==(other) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/konduto-ruby/konduto_base.rb', line 49

def ==(other)
  self.instance_variables.each do |name|
    return false unless self.instance_variable_get(name) == other.instance_variable_get(name)
  end

  true
end

#to_hashObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/konduto-ruby/konduto_base.rb', line 26

def to_hash
  Hash[
    instance_variables.map do |name|
      value = instance_variable_get(name)

      if value.respond_to? :each
        value = value.map {|v| v.to_hash }
      elsif !value.instance_variables.empty?
        value = value.to_hash
      elsif value.is_a?(Date) || value.is_a?(Symbol)
        value = value.to_s
      end

      [name == :@klass ? 'class' : name.to_s.gsub(/^@/, ''), value]
    end
  ]
end

#to_jsonObject

Raises:

  • (RuntimeError)


44
45
46
47
# File 'lib/konduto-ruby/konduto_base.rb', line 44

def to_json
  raise RuntimeError, 'Invalid object for serialization' unless self.valid?
  self.to_hash.to_json
end