Class: Tanakai::BrowserBuilder::ApparitionBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/tanakai/browser_builder/apparition_builder.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config, spider:) ⇒ ApparitionBuilder

Returns a new instance of ApparitionBuilder.



10
11
12
13
14
# File 'lib/tanakai/browser_builder/apparition_builder.rb', line 10

def initialize(config, spider:)
  @config = config
  @spider = spider
  @logger = spider.logger
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



8
9
10
# File 'lib/tanakai/browser_builder/apparition_builder.rb', line 8

def logger
  @logger
end

#spiderObject (readonly)

Returns the value of attribute spider.



8
9
10
# File 'lib/tanakai/browser_builder/apparition_builder.rb', line 8

def spider
  @spider
end

Instance Method Details

#buildObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/tanakai/browser_builder/apparition_builder.rb', line 16

def build
  # Register driver
  Capybara.register_driver :apparition do |app|
    timeout = ENV.fetch('TIMEOUT', 30).to_i
    driver_options = { js_errors: false, timeout: timeout, debug: ENV['DEBUG'] }

    driver_options[:headless] = ENV.fetch("HEADLESS", "true") == "true"
    logger.debug "BrowserBuilder (apparition): enabled extensions"

    Capybara::Apparition::Driver.new(app, driver_options)
  end

  # Create browser instance (Capybara session)
  @browser = Capybara::Session.new(:apparition)
  @browser.spider = spider
  logger.debug "BrowserBuilder (apparition): created browser instance"

  # Headers
  if headers = @config[:headers].presence
    @browser.driver.headers = headers
    logger.debug "BrowserBuilder (apparition): enabled custom headers"
  end

  if user_agent = @config[:user_agent].presence
    user_agent_string = (user_agent.class == Proc ? user_agent.call : user_agent).strip

    @browser.driver.add_header("User-Agent", user_agent_string)
    logger.debug "BrowserBuilder (apparition): enabled custom user_agent"
  end

  # Cookies
  if cookies = @config[:cookies].presence
    cookies.each do |cookie|
      @browser.driver.set_cookie(cookie[:name], cookie[:value], cookie)
    end

    logger.debug "BrowserBuilder (apparition): enabled custom cookies"
  end

  @browser
end