Class: Whatser::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/whatser/resources/resource.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Resource

Returns a new instance of Resource.



45
46
47
# File 'lib/whatser/resources/resource.rb', line 45

def initialize(params={})
  params.each_pair { |k,v| send("#{k}=", v) if respond_to?(k) }
end

Instance Attribute Details

#jsonObject

Returns the value of attribute json.



3
4
5
# File 'lib/whatser/resources/resource.rb', line 3

def json
  @json
end

Class Method Details

.api_request(verb, path, params = {}, opts = {}) ⇒ Object



15
16
17
18
19
# File 'lib/whatser/resources/resource.rb', line 15

def api_request(verb, path, params={}, opts={})
  res = client.request(verb, path, params)
  res.data = convert_data_to_model( res.data, opts)
  return res
end

.clientObject



6
7
8
# File 'lib/whatser/resources/resource.rb', line 6

def client
  @client
end

.convert_data_to_model(data, opts = {}) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/whatser/resources/resource.rb', line 21

def convert_data_to_model(data, opts={})
  return data if data.blank?
  opts ||= {}

  data = if data.is_a?(Array)
    data.inject([]) {|result,d| result << from_hash_to_model(d, opts[:model]) }
  else
    from_hash_to_model(data, opts[:model])
  end
  data
end

.from_hash_to_model(hash, model = nil) ⇒ Object



33
34
35
36
37
38
39
40
41
42
# File 'lib/whatser/resources/resource.rb', line 33

def from_hash_to_model(hash, model=nil)
  hash ||= {}
  hash = hash.size == 1 ? hash.first.last : hash
  mod = model.blank? ? new : model.new
  hash.each do |k,v|
    mod.send("#{k}=", v) if mod.respond_to?(k)
  end
  mod.json = hash.to_json
  return mod
end

.set(client) ⇒ Object



10
11
12
13
# File 'lib/whatser/resources/resource.rb', line 10

def set(client)
  @client = client
  self
end

Instance Method Details

#api_request(verb, path, params = {}, opts = {}) ⇒ Object



49
50
51
# File 'lib/whatser/resources/resource.rb', line 49

def api_request(verb, path, params={}, opts={})
  self.class.api_request(verb, path, params, opts)
end