Class: RemotePartial::ResourceManager

Inherits:
Object
  • Object
show all
Defined in:
app/models/remote_partial/resource_manager.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, criteria = nil) ⇒ ResourceManager

Returns a new instance of ResourceManager.



27
28
29
30
# File 'app/models/remote_partial/resource_manager.rb', line 27

def initialize(url, criteria = nil)
  @url = url
  @criteria = criteria
end

Instance Attribute Details

#criteriaObject (readonly)

Returns the value of attribute criteria.



6
7
8
# File 'app/models/remote_partial/resource_manager.rb', line 6

def criteria
  @criteria
end

#urlObject (readonly)

Returns the value of attribute url.



6
7
8
# File 'app/models/remote_partial/resource_manager.rb', line 6

def url
  @url
end

Class Method Details

.get_page(url) ⇒ Object



8
9
10
# File 'app/models/remote_partial/resource_manager.rb', line 8

def self.get_page(url)
  Nokogiri::HTML(get_raw(url))
end

.get_raw(url) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'app/models/remote_partial/resource_manager.rb', line 12

def self.get_raw(url)
  response = Net::HTTP.get_response(URI(url))
  
  case response.code.to_i
  when ok_response_codes
    return response.body
  when redirect_response_codes
    get_raw(URI.parse(response['location']))
  else
    raise response.inspect
  end
rescue => exception # Do main exception raising outside of case statement so that SocketErrors are also handled
  raise RemotePartialRetrivalError.new(url, exception)
end

Instance Method Details

#htmlObject



32
33
34
35
36
37
38
# File 'app/models/remote_partial/resource_manager.rb', line 32

def html
  if criteria
    self.class.get_page(@url).search(criteria).to_s
  else
    self.class.get_raw(@url).force_encoding('UTF-8')
  end
end

#output_to(path) ⇒ Object



40
41
42
43
44
# File 'app/models/remote_partial/resource_manager.rb', line 40

def output_to(path)
  @path = path
  ensure_output_folder_exists
  File.write(path, html)
end