Class: CorePro::Models::JsonBase

Inherits:
Object
  • Object
show all
Defined in:
lib/corepro/models/json_base.rb

Instance Method Summary collapse

Instance Method Details

#from_json!(json, classDefs = nil) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/corepro/models/json_base.rb', line 57

def from_json! json, classDefs = nil
  classDefs = classDefs || {}
  json.each do |var, val|
    # if self.instance_variable_defined?("@#{var}")
    cd = nil
    cd = classDefs[var] if classDefs.has_key? var
    if cd == nil
      self.instance_variable_set "@#{var}", val
    else
      if val.kind_of?(Array)
        arr = []
        val.each do |x|
          item = cd.new
          item.from_json! x, nil
          arr.push item
        end
        self.instance_variable_set "@#{var}", arr
      elsif cd.new.is_hash?
      # elsif val.kind_of?(Hash)
        hash = {}
        val.each do |key, itemJson|
          item = cd.new
          item.from_json! itemJson, nil
          hash[key] = item
        end
        self.instance_variable_set "@#{var}", hash
      else
        item = cd.new
        item.from_json! val, nil
        self.instance_variable_set "@#{var}", item
      end
    end
  end
end

#is_hash?Boolean

Returns:

  • (Boolean)


6
7
8
# File 'lib/corepro/models/json_base.rb', line 6

def is_hash?
  false
end

#to_hashObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/corepro/models/json_base.rb', line 10

def to_hash
  hash = {}
  self.instance_variables.each do |var|
    val = self.instance_variable_get var
    if val != nil
      if val.instance_of?(Array)
        arr = []
        val.each do |x|
          arr.push(x.to_hash)
        end
        hash[var.to_s.delete('@')] = arr
      else
        hash[var.to_s.delete('@')] = val
      end
    end
  end

  hash
end

#to_jsonObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/corepro/models/json_base.rb', line 30

def to_json
  hash = {}
  self.instance_variables.each do |var|
    val = self.instance_variable_get var
    if val != nil
      if val.instance_of?(String)
        hash[var.to_s.delete('@')] = val
      elsif val.instance_of?(Array)
        # do not serialize empty arrays.  no point.
        if val.length > 0
          arr = []
          val.each do |x|
            h = x.to_hash
            arr.push h
          end
          hash[var.to_s.delete('@')] = arr
        end
      else
        hash[var.to_s.delete('@')] = val.to_json
      end
    end
  end
  hash.to_json
end