Class: HypermediaAPI::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/api/model.rb

Class Method Summary collapse

Class Method Details

.authObject



4
5
6
# File 'lib/api/model.rb', line 4

def self.auth
  @auth ||= { username: '', password: '' }
end

.authorize(username, password) ⇒ Object



8
9
10
# File 'lib/api/model.rb', line 8

def self.authorize (username, password)
  @auth = { username: username, password: password }
end

.inherited(subclass) ⇒ Object



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

def self.inherited (subclass)
  subclass.authorize(self.auth[:username], self.auth[:password])
  subclass.root_url(@root_url)
end

.new_from_fields(field_elements) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/api/model.rb', line 17

def self.new_from_fields (field_elements)
  instance = self.new
  
  field_elements.each do |field_element|
    value_str = field_element.content
    name = field_element['data-name']
    
    value = case field_element['data-type']
      when 'date' then value_str.empty? ? nil : Date.parse(value_str)
      when 'integer' then value_str.empty? ? nil : value_str.to_i
      when 'float' then value_str.empty? ? nil : value_str.to_f
      when 'boolean' then value_str.empty? ? nil : value_str != 'false'
      when 'string' then value_str
    end
    
    if instance.respond_to?(name)
      instance.send(:"#{name}=", value)
    end
  end
  
  instance
end

.query(query_name, form_values) ⇒ Object



48
49
50
51
# File 'lib/api/model.rb', line 48

def self.query (query_name, form_values)
  query_form = self.root_doc.form("##{query_name.to_s.dasherize}")
  query_form.submit(form_values, basic_auth: self.auth)
end

.root_docObject



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

def self.root_doc
  @root_doc ||= HypermediaAPI.get(@root_url, basic_auth: self.auth)
end

.root_url(url) ⇒ Object



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

def self.root_url (url)
  @root_url = url
end