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, define_strftime_pattern

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



55
56
57
58
59
60
61
# File 'lib/konduto-ruby/konduto_base.rb', line 55

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

  true
end

#defined_strftime_pattern(attr) ⇒ Object



67
68
69
# File 'lib/konduto-ruby/konduto_base.rb', line 67

def defined_strftime_pattern(attr)
  send("#{attr.to_s.gsub(/^@/, '')}_strftime_pattern")
end

#defined_strftime_pattern?(attr) ⇒ Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/konduto-ruby/konduto_base.rb', line 63

def defined_strftime_pattern?(attr)
  respond_to? "#{attr.to_s.gsub(/^@/, '')}_strftime_pattern"
end

#to_hashObject



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

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

      strftime_pattern = defined_strftime_pattern(name) if defined_strftime_pattern?(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?(DateTime)
        value = value.strftime(strftime_pattern || '%Y-%m-%dT%H:%MZ')
      elsif value.is_a?(Date)
        value = value.strftime(strftime_pattern || '%Y-%m-%d')
      elsif value.is_a?(Symbol)
        value = value.to_s
      end

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

#to_jsonObject

Raises:

  • (RuntimeError)


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

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