Class: HypermediaAPI::Document

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

Instance Method Summary collapse

Constructor Details

#initialize(nokogiri_html_document, status, headers, auth) ⇒ Document

Returns a new instance of Document.



35
36
37
38
39
40
# File 'lib/api/document.rb', line 35

def initialize (nokogiri_html_document, status, headers, auth)
  @document = nokogiri_html_document
  @status = status.to_i
  @headers = headers
  @auth = auth
end

Instance Method Details

#entities(klass) ⇒ Object



11
12
13
14
# File 'lib/api/document.rb', line 11

def entities (klass)
  article_elements = @document.css("article.#{klass.name.underscore}")
  article_elements.map {|article_element| klass.new_from_fields(article_element.element_children.filter('code')) }
end

#entity(klass) ⇒ Object



4
5
6
7
8
9
# File 'lib/api/document.rb', line 4

def entity (klass)
  article_element = @document.at_css("article.#{klass.name.underscore}")
  return nil unless article_element
  
  klass.new_from_fields(article_element.element_children.filter('code'))
end

#form(css_selector) ⇒ Object



16
17
18
19
20
21
22
23
24
25
# File 'lib/api/document.rb', line 16

def form (css_selector)
  if form_element = @document.at_css(css_selector)
    action_uri = form_element['action']
    http_method = form_element['method'].downcase
    
    HypermediaAPI::Form.new(action_uri, http_method)
  else
    raise HypermediaAPI::MissingForm, "The API does not have a form matching '#{css_selector}'."
  end
end

#headersObject



27
28
29
# File 'lib/api/document.rb', line 27

def headers
  @headers
end

#htmlObject



31
32
33
# File 'lib/api/document.rb', line 31

def html
  @document.to_html
end


42
43
44
45
46
47
48
49
# File 'lib/api/document.rb', line 42

def link (css_selector)
  if a_element = @document.at_css(css_selector)
    href_uri = a_element['href']
    HypermediaAPI::Link.new(href_uri)
  else
    raise HypermediaAPI::MissingLink, "The API does not have a link matching '#{css_selector}'."
  end
end

#look_up_entity(klass, kv_pair) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/api/document.rb', line 51

def look_up_entity (klass, kv_pair)
  index_link = self.link("nav#index-links a##{klass.name.underscore.pluralize}-link")
  index_doc = index_link.click(basic_auth: @auth)
  
  data_name, value = kv_pair.first
  article_element = index_doc.instance_variable_get(:@document).at_xpath("//article[@class='#{klass.name.underscore}']/code[@data-name='#{data_name}' and text()='#{value}']/ancestor::article")
  return nil unless article_element
  
  bookmark_link_element = article_element.at_css('a[rel="bookmark"]')
  bookmark_link = HypermediaAPI::Link.new(bookmark_link_element['href'])
  entity_doc = bookmark_link.click(basic_auth: @auth)
  
  entity_doc.entity(klass)
end

#statusObject



66
67
68
# File 'lib/api/document.rb', line 66

def status
  @status
end