Class: AlexaSkillsRuby::JsonObject

Inherits:
Object
  • Object
show all
Defined in:
lib/alexa_skills_ruby/json_object.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ JsonObject

Returns a new instance of JsonObject.



40
41
42
# File 'lib/alexa_skills_ruby/json_object.rb', line 40

def initialize(attrs = {})
  populate_from_json(attrs)
end

Class Method Details

.attribute(*attrs) ⇒ Object Also known as: attributes



19
20
21
22
23
24
# File 'lib/alexa_skills_ruby/json_object.rb', line 19

def self.attribute(*attrs)
  attrs.compact.map { |a| a.to_sym }.each do |a|
    attr_accessor a
    self._properties << a
  end
end

.inherited(subclass) ⇒ Object

Copy properties on inheritance.



32
33
34
35
36
37
38
# File 'lib/alexa_skills_ruby/json_object.rb', line 32

def self.inherited(subclass)
  entities = _json_object_properties.dup
  attrs = _properties.dup
  subclass._json_object_properties = entities.each { |k, v| entities[k] = v.dup }
  subclass._properties = attrs
  super
end

.json_object_attribute(*args) ⇒ Object Also known as: json_object_attributes



9
10
11
12
13
14
15
16
17
# File 'lib/alexa_skills_ruby/json_object.rb', line 9

def self.json_object_attribute(*args)
  klass = args.pop
  raise "Invalid arguments" unless klass && klass.is_a?(Class) && args.length > 0

  args.compact.map { |a| a.to_sym }.each do |a|
    attr_accessor a
    self._json_object_properties[a.to_sym] = klass
  end
end

Instance Method Details

#as_json(options = nil) ⇒ Object



44
45
46
# File 'lib/alexa_skills_ruby/json_object.rb', line 44

def as_json(options = nil)
  serialize_attributes(_properties + _json_object_properties.keys)
end

#populate_from_json(attrs) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/alexa_skills_ruby/json_object.rb', line 52

def populate_from_json(attrs)
  return unless attrs

  attrs.each do |k, v|
    meth = "#{get_method_name(k)}=".to_sym
    if self.respond_to? meth
      if json_object_class = _json_object_properties[k.to_sym]
        assign_json_object(meth, v, json_object_class)
      else
        self.send(meth, v)
      end
    end
  end
end

#serialize_attributes(attrs) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/alexa_skills_ruby/json_object.rb', line 67

def serialize_attributes(attrs)
  json = {}
  attrs.each do |k|
    meth = k.to_sym
    if self.respond_to?(meth)
      if _json_object_properties[k.to_sym]
        val = serialize_json_object(meth)
      else
        val = self.send(meth)
      end
      unless val.nil?
        json[get_attribute_name(k)] = val
      end
    end
  end
  json
end

#to_json(options = nil) ⇒ Object



48
49
50
# File 'lib/alexa_skills_ruby/json_object.rb', line 48

def to_json(options = nil)
  MultiJson.dump(as_json(options))
end