Class: Tr4n5l4te::Agent

Inherits:
Object
  • Object
show all
Defined in:
lib/tr4n5l4te/agent.rb

Constant Summary collapse

DEFAULT_UA =

rubocop:disable Metrics/LineLength

'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Agent

Returns a new instance of Agent.



28
29
30
31
32
# File 'lib/tr4n5l4te/agent.rb', line 28

def initialize(options = {})
  Capybara.ignore_hidden_elements = false
  @browser = options[:browser] || Capybara.current_session
  browser.driver.headers = { 'User-Agent' => DEFAULT_UA }
end

Instance Attribute Details

#browserObject (readonly)

rubocop:enable Metrics/LineLength



26
27
28
# File 'lib/tr4n5l4te/agent.rb', line 26

def browser
  @browser
end

Instance Method Details

#bodyObject



81
82
83
# File 'lib/tr4n5l4te/agent.rb', line 81

def body
  browser.body
end

#cookiesObject



72
73
74
# File 'lib/tr4n5l4te/agent.rb', line 72

def cookies
  browser.driver.cookies
end

#elements(selector_string) ⇒ Object



85
86
87
# File 'lib/tr4n5l4te/agent.rb', line 85

def elements(selector_string)
  browser.all(selector_string)
end

#load_cookies(cookie_file) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/tr4n5l4te/agent.rb', line 34

def load_cookies(cookie_file)
  return false unless cookie_hash = YAML.safe_load(
    File.read(cookie_file), permitted_classes: [Capybara::Poltergeist::Cookie]
  )

  browser.driver.clear_cookies
  cookie_hash.each do |key, cookie_obj|
    browser.driver.set_cookie(
      key,
      cookie_obj.value,
      domain: cookie_obj.domain,
      path: cookie_obj.path,
      secure: cookie_obj.secure?,
      httponly: cookie_obj.httponly?,
      expires: cookie_obj.expires
    )
  end
end


60
61
62
63
64
65
66
67
68
69
70
# File 'lib/tr4n5l4te/agent.rb', line 60

def set_cookie(name, value, options = {})
  browser.driver.set_cookie(
    name.to_s,
    value.to_s,
    domain: options.fetch(:domain, nil),
    path: options.fetch(:path, nil),
    secure: options.fetch(:secure, false),
    httponly: options.fetch(:httponly, false),
    expires: options.fetch(:expires, time_plus_years)
  )
end

#store_cookies(cookie_file) ⇒ Object

rubocop:enable



54
55
56
57
58
# File 'lib/tr4n5l4te/agent.rb', line 54

def store_cookies(cookie_file)
  FileUtils.mkdir_p(File.dirname(cookie_file))
  data = YAML.dump(browser.driver.cookies)
  File.open(cookie_file, 'w') { |f| f.write(data) }
end

#visit(url) ⇒ Object



76
77
78
79
# File 'lib/tr4n5l4te/agent.rb', line 76

def visit(url)
  response = browser.visit(url)
  response.recursively_symbolize_keys!
end