Class: Red5::Entities

Inherits:
Object
  • Object
show all
Defined in:
lib/red_5/models/entities.rb

Direct Known Subclasses

Films, People, Planets, Species, Starships, Vehicles

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Entities

Returns a new instance of Entities.



20
21
22
23
# File 'lib/red_5/models/entities.rb', line 20

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



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/red_5/models/entities.rb', line 29

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

.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

.firstObject



16
17
18
# File 'lib/red_5/models/entities.rb', line 16

def self.first
  self.find 1
end

Instance Method Details

#[](key) ⇒ Object



25
26
27
# File 'lib/red_5/models/entities.rb', line 25

def [] key
  @data[key] || raise(Red5Exception.new "No such attribute #{key}")
end