Module: RatPackSwagger::Definition

Defined in:
lib/rat_pack_swagger.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(mod) ⇒ Object



38
39
40
# File 'lib/rat_pack_swagger.rb', line 38

def self.included mod
  mod.extend DefinitionClass
end

Instance Method Details

#from_h(h) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rat_pack_swagger.rb', line 42

def from_h(h)
  properties = self.class.definition[:properties] 
  h.each do |k,v|
    k = k.to_sym
    setter = "#{k}="
    if properties.keys.include?(k)
      # if property type references another class, instantiate it and use hash data to populate it
      if properties[k][:$ref]
        send(setter, properties[k][:$ref].new.from_h(v))
      # if property type is an ARRAY that references another class, instantiate and use hash data to populate them
      elsif properties[k][:type].to_sym == :array && properties[k][:items][:$ref]
        send(setter, v.map{|_| properties[k][:items][:$ref].new.from_h(_) })
      else
        send(setter, v)
      end
    end
  end
  return self
end

#to_h(recur = true) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/rat_pack_swagger.rb', line 61

def to_h(recur = true)
  h = {}
  self.class.definition[:properties].keys.each do |p|
    val = send(p)
    if recur
      if val.is_a?(Array)
        h[p] = val.map{|v| v.is_a?(Definition) ? v.to_h : v}
      elsif val.is_a?(Definition)
        h[p] = val.to_h
      else
        h[p] = val
      end
    else 
      h[p] = val
    end
  end
  return h
end