class Red5::Entities

Public Class Methods

all() click to toggle source
# 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}/"
  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) click to toggle source
# 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() click to toggle source
# File lib/red_5/models/entities.rb, line 16
def self.first
  self.find 1
end
new(data) click to toggle source
# File lib/red_5/models/entities.rb, line 42
def initialize data
  @data = data
  @data['id'] = @data['url'].split('/').last.to_i
end

Public Instance Methods

[](key) click to toggle source
# File lib/red_5/models/entities.rb, line 47
def [] key
  @data[key] || raise(Red5Exception.new "No such attribute #{key}")
end
method_missing(method_name, *args) click to toggle source
# 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