Module: CiscoSpark::Model::ClassMethods

Defined in:
lib/cisco_spark/model.rb

Instance Method Summary collapse

Instance Method Details

#attributes(hash = nil) ⇒ Object



18
19
20
21
22
23
# File 'lib/cisco_spark/model.rb', line 18

def attributes(hash=nil)
  return @attributes unless hash

  @attributes = hash
  attr_accessor *@attributes.keys
end

#create(attributes) ⇒ Object



44
45
46
47
# File 'lib/cisco_spark/model.rb', line 44

def create(attributes)
  response = Api.new.post(@resource, attributes)
  parse(response.body)
end

#destroy(id) ⇒ Object



55
56
57
# File 'lib/cisco_spark/model.rb', line 55

def destroy(id)
  Api.new.delete("#{@resource}/#{id}")
end

#fetch(id, options = {}) ⇒ Object



39
40
41
42
# File 'lib/cisco_spark/model.rb', line 39

def fetch(id, options={})
  response = Api.new.get("#{@resource}/#{id}", options)
  parse(response.body)
end

#fetch_all(options = {}) ⇒ Object



33
34
35
36
37
# File 'lib/cisco_spark/model.rb', line 33

def fetch_all(options={})
  response = fetch_all_raw(options)
  collection = parse_collection(response.body)
  CiscoSpark::Collection.new(self, collection, response)
end

#fetch_all_raw(options = {}) ⇒ Object



29
30
31
# File 'lib/cisco_spark/model.rb', line 29

def fetch_all_raw(options={})
  Api.new.get(@resource, options)
end

#mutable_attributes(*attributes) ⇒ Object



25
26
27
# File 'lib/cisco_spark/model.rb', line 25

def mutable_attributes(*attributes)
  @mutable_attributes = attributes
end

#parse(hash) ⇒ Object



65
66
67
68
69
70
71
# File 'lib/cisco_spark/model.rb', line 65

def parse(hash)
  hash = JSON.parse(hash) if hash.is_a?(String)
  params = attributes.each_with_object({}) do |(attribute, caster), params|
    params[attribute] = caster.call(hash[Utils.camelize(attribute)])
  end
  new(params)
end

#parse_collection(object) ⇒ Object



59
60
61
62
63
# File 'lib/cisco_spark/model.rb', line 59

def parse_collection(object)
  object = JSON.parse(object) if object.is_a?(String)
  object = object.fetch('items', []) if object.is_a?(Hash)
  object.map{ |hash| parse(hash) }
end

#resource(resource = nil) ⇒ Object



12
13
14
15
16
# File 'lib/cisco_spark/model.rb', line 12

def resource(resource=nil)
  return @resource unless resource

  @resource = resource
end

#update(id, attributes) ⇒ Object



49
50
51
52
53
# File 'lib/cisco_spark/model.rb', line 49

def update(id, attributes)
  attributes = attributes.select{ |name, _v| @mutable_attributes.include?(name) }
  response = Api.new.put("#{@resource}/#{id}", attributes)
  parse(response.body)
end