Class: Red5::Entities
- Inherits:
-
Object
show all
- Defined in:
- lib/red_5/models/entities.rb
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(data) ⇒ Entities
Returns a new instance of Entities.
42
43
44
45
|
# File 'lib/red_5/models/entities.rb', line 42
def initialize data
@data = data
@data['id'] = @data['url'].split('/').last.to_i
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *args) ⇒ Object
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
# File 'lib/red_5/models/entities.rb', line 51
def method_missing method_name, *args
mname = method_name.to_s
parts = mname.split('_')
case parts[0]
when 'fetch'
key = parts[1]
url = self[key]
unless url.is_a? Array
expects_single_result = true
url = [url]
end
results = []
url.each do |u|
results.push Red5.fetch_results u
end
return results.first if expects_single_result
results
end
end
|
Class Method Details
.all ⇒ Object
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
# File 'lib/red_5/models/entities.rb', line 20
def self.all
list = []
basename = self.name.split('::').last
slug = basename.downcase
resource = RestClient::Resource.new "http://swapi.co/api/#{slug}/?page=1"
has_more = true
while has_more
data = resource.get.body
j = JSON.parse data
list += j['results']
if j['next']
resource = RestClient::Resource.new j['next']
else
has_more = false
end
end
list.map { |i| self.new i }
end
|
.find(id) ⇒ Object
3
4
5
6
7
8
9
10
11
12
13
14
|
# File 'lib/red_5/models/entities.rb', line 3
def self.find id
basename = self.name.split('::').last
slug = basename.downcase
resource = RestClient::Resource.new "http://swapi.co/api/#{slug}/#{id}"
begin
self.new JSON.parse resource.get.body
rescue RestClient::ResourceNotFound
id = "##{id}" if id.is_a? Numeric
raise Red5Exception.new "#{basename.singularize} #{id} does not exist"
end
end
|
.first ⇒ Object
16
17
18
|
# File 'lib/red_5/models/entities.rb', line 16
def self.first
self.find 1
end
|
Instance Method Details
#[](key) ⇒ Object
47
48
49
|
# File 'lib/red_5/models/entities.rb', line 47
def [] key
@data[key] || raise(Red5Exception.new "No such attribute #{key}")
end
|