Skip to content

Commit

Permalink
* Fix rubocop warnings
Browse files Browse the repository at this point in the history
* Bump Ruby to 2.6 as 2.5 is EOL
  • Loading branch information
route committed Nov 4, 2021
1 parent e10ed1d commit e45da11
Show file tree
Hide file tree
Showing 19 changed files with 82 additions and 80 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
fail-fast: false
matrix:
gemfile: [websocket-driver-0.6.x, websocket-driver-0.7.x]
ruby: [2.5, 2.6, 2.7, 3.0]
ruby: [2.6, 2.7, 3.0]

runs-on: ubuntu-latest
env:
Expand Down
16 changes: 11 additions & 5 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
inherit_from: .rubocop_todo.yml

AllCops:
TargetRubyVersion: 2.5
TargetRubyVersion: 2.6
NewCops: enable

Layout/FirstArrayElementIndentation:
Expand All @@ -16,13 +16,19 @@ Metrics/BlockLength:
- "*.gemspec"

Naming/MethodParameterName:
MinNameLength: 2
AllowedNames:
- x
- y
- id
- to
- on

Naming/FileName:
Exclude:
- 'gemfiles/websocket-driver-*.gemfile'
- 'gemfiles/*.gemfile'

Style/MultilineBlockChain:
Exclude:
- spec/**/*

Metrics/ModuleLength:
Exclude:
- spec/**/*
8 changes: 0 additions & 8 deletions .rubocop_todo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,6 @@ Metrics/ModuleLength:
Metrics/PerceivedComplexity:
Max: 14

# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: Keywords.
# Keywords: TODO, FIXME, OPTIMIZE, HACK, REVIEW
Style/CommentAnnotation:
Exclude:
- 'spec/node_spec.rb'

# Offense count: 45
Style/Documentation:
Enabled: false
Expand Down
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -858,9 +858,10 @@ browser.add_script_tag(url: "http://example.com/stylesheet.css") # => true
browser.add_style_tag(content: "h1 { font-size: 40px; }") # => true

```
#### bypass_csp(enabled) : `Boolean`
#### bypass_csp(\*\*options) : `Boolean`

* enabled `Boolean`, `true` by default
* options `Hash`
* :enabled `Boolean`, `true` by default

```ruby
browser.bypass_csp # => true
Expand Down Expand Up @@ -1001,7 +1002,7 @@ browser.go_to("https://www.w3schools.com/tags/tag_frame.asp")
browser.main_frame.doctype # => "<!DOCTYPE html>"
```

#### set_content(html)
#### content = html

Sets a content of a given frame.

Expand All @@ -1011,7 +1012,7 @@ Sets a content of a given frame.
browser.go_to("https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe")
frame = browser.frames[1]
frame.body # <html lang="en"><head><style>body {transition: opacity ease-in 0.2s; }...
frame.set_content("<html><head></head><body><p>lol</p></body></html>")
frame.content = "<html><head></head><body><p>lol</p></body></html>"
frame.body # => <html><head></head><body><p>lol</p></body></html>
```

Expand Down
2 changes: 1 addition & 1 deletion ferrum.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Gem::Specification.new do |s|
"source_code_uri" => "https://github.com/rubycdp/ferrum"
}

s.required_ruby_version = ">= 2.5.0"
s.required_ruby_version = ">= 2.6.0"

s.add_runtime_dependency "addressable", "~> 2.5"
s.add_runtime_dependency "cliver", "~> 0.3"
Expand Down
2 changes: 1 addition & 1 deletion lib/ferrum/browser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class Browser
delegate %i[targets create_target page pages windows] => :default_context
delegate %i[go_to back forward refresh reload stop wait_for_reload
at_css at_xpath css xpath current_url current_title url title
body doctype set_content
body doctype content=
headers cookies network
mouse keyboard
screenshot pdf mhtml viewport_size
Expand Down
16 changes: 8 additions & 8 deletions lib/ferrum/browser/process.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def initialize(options)
if options[:url]
url = URI.join(options[:url].to_s, "/json/version")
response = JSON.parse(::Net::HTTP.get(url))
set_ws_url(response["webSocketDebuggerUrl"])
self.ws_url = response["webSocketDebuggerUrl"]
parse_browser_versions
return
end
Expand Down Expand Up @@ -142,22 +142,22 @@ def parse_ws_url(read_io, timeout)
begin
output += read_io.read_nonblock(512)
rescue IO::WaitReadable
IO.select([read_io], nil, nil, max_time - now)
read_io.wait_readable(max_time - now)
else
if output.match(regexp)
set_ws_url(output.match(regexp)[1].strip)
self.ws_url = output.match(regexp)[1].strip
break
end
end
end

unless ws_url
@logger&.puts(output)
raise ProcessTimeoutError.new(timeout, output)
end
return if ws_url

@logger&.puts(output)
raise ProcessTimeoutError.new(timeout, output)
end

def set_ws_url(url)
def ws_url=(url)
@ws_url = Addressable::URI.parse(url)
@host = @ws_url.host
@port = @ws_url.port
Expand Down
3 changes: 2 additions & 1 deletion lib/ferrum/frame.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,15 @@ def main?
@parent_id.nil?
end

def set_content(html)
def content=(html)
evaluate_async(%(
document.open();
document.write(arguments[0]);
document.close();
arguments[1](true);
), @page.timeout, html)
end
alias set_content content=

def execution_id?(execution_id)
@execution_id == execution_id
Expand Down
6 changes: 1 addition & 5 deletions lib/ferrum/frame/runtime.rb
Original file line number Diff line number Diff line change
Expand Up @@ -181,11 +181,7 @@ def handle_response(response)
Node.new(self, @page.target_id, node_id, description)
when "array"
reduce_props(object_id, []) do |memo, key, value|
next(memo) unless begin
Integer(key)
rescue StandardError
nil
end
next(memo) unless Integer(key, exception: false)

value = value["objectId"] ? handle_response(value) : value["value"]
memo.insert(key.to_i, value)
Expand Down
10 changes: 5 additions & 5 deletions lib/ferrum/keyboard.rb
Original file line number Diff line number Diff line change
Expand Up @@ -77,19 +77,19 @@ def normalize_keys(keys, pressed_keys = [], memo = [])
pressed_keys.last.push(key)
nil
else
_key = KEYS.fetch(KEYS_MAPPING[key.to_sym] || key.to_sym)
_key[:modifiers] = pressed_keys.flatten.map { |k| MODIFIERS[k] }.reduce(0, :|)
to_options(_key)
key = KEYS.fetch(KEYS_MAPPING[key.to_sym] || key.to_sym)
key[:modifiers] = pressed_keys.flatten.map { |k| MODIFIERS[k] }.reduce(0, :|)
to_options(key)
end
when String
pressed = pressed_keys.flatten
keys.each_char.map do |char|
key = KEYS[char] || {}

if pressed.empty?
key = KEYS[char] || {}
key = key.merge(text: char, unmodifiedText: char)
[to_options(key)]
else
key = KEYS[char] || {}
text = pressed == ["shift"] ? char.upcase : char
key = key.merge(
text: text,
Expand Down
4 changes: 2 additions & 2 deletions lib/ferrum/mouse.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ def move(x:, y:, steps: 1)
@y = y

steps.times do |i|
new_x = from_x + (@x - from_x) * ((i + 1) / steps.to_f)
new_y = from_y + (@y - from_y) * ((i + 1) / steps.to_f)
new_x = from_x + ((@x - from_x) * ((i + 1) / steps.to_f))
new_y = from_y + ((@y - from_y) * ((i + 1) / steps.to_f))

@page.command("Input.dispatchMouseEvent",
slowmoable: true,
Expand Down
15 changes: 8 additions & 7 deletions lib/ferrum/network.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ class Network
RESOURCE_TYPES = %w[Document Stylesheet Image Media Font Script TextTrack
XHR Fetch EventSource WebSocket Manifest
SignedExchange Ping CSPViolationReport Other].freeze
AUTHORIZE_BLOCK_MISSING = "Block is missing, call `authorize(...) { |r| r.continue } "\
"or subscribe to `on(:request)` events before calling it"
AUTHORIZE_TYPE_WRONG = ":type should be in #{AUTHORIZE_TYPE}"

attr_reader :traffic

Expand Down Expand Up @@ -95,12 +98,8 @@ def intercept(pattern: "*", resource_type: nil)
end

def authorize(user:, password:, type: :server, &block)
raise ArgumentError, ":type should be in #{AUTHORIZE_TYPE}" unless AUTHORIZE_TYPE.include?(type)

if !block_given? && !@page.subscribed?("Fetch.requestPaused")
raise ArgumentError,
"Block is missing, call `authorize(...) { |r| r.continue } or subscribe to `on(:request)` events before calling it"
end
raise ArgumentError, AUTHORIZE_TYPE_WRONG unless AUTHORIZE_TYPE.include?(type)
raise ArgumentError, AUTHORIZE_BLOCK_MISSING if !block_given? && !@page.subscribed?("Fetch.requestPaused")

@authorized_ids ||= {}
@authorized_ids[type] ||= []
Expand Down Expand Up @@ -154,7 +153,9 @@ def subscribe
end

@page.on("Network.responseReceived") do |params|
if exchange = select(params["requestId"]).last
exchange = select(params["requestId"]).last

if exchange
response = Network::Response.new(@page, params)
exchange.response = response
end
Expand Down
6 changes: 5 additions & 1 deletion lib/ferrum/network/auth_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,11 @@ def referrer_policy
end

def inspect
%(#<#{self.class} @request_id=#{@request_id.inspect} @frame_id=#{@frame_id.inspect} @resource_type=#{@resource_type.inspect} @request=#{@request.inspect}>)
"#<#{self.class} "\
"@request_id=#{@request_id.inspect} "\
"@frame_id=#{@frame_id.inspect} "\
"@resource_type=#{@resource_type.inspect} "\
"@request=#{@request.inspect}>"
end
end
end
Expand Down
6 changes: 5 additions & 1 deletion lib/ferrum/network/intercepted_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@ def referrer_policy
end

def inspect
%(#<#{self.class} @request_id=#{@request_id.inspect} @frame_id=#{@frame_id.inspect} @resource_type=#{@resource_type.inspect} @request=#{@request.inspect}>)
"#<#{self.class} "\
"@request_id=#{@request_id.inspect} "\
"@frame_id=#{@frame_id.inspect} "\
"@resource_type=#{@resource_type.inspect} "\
"@request=#{@request.inspect}>"
end

private
Expand Down
22 changes: 11 additions & 11 deletions lib/ferrum/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,15 @@ def focusable?

def wait_for_stop_moving(delay: MOVING_WAIT_DELAY, attempts: MOVING_WAIT_ATTEMPTS)
Ferrum.with_attempts(errors: NodeMovingError, max: attempts, wait: 0) do
previous, current = get_content_quads_with(delay: delay)
previous, current = content_quads_with(delay: delay)
raise NodeMovingError.new(self, previous, current) if previous != current

current
end
end

def moving?(delay: MOVING_WAIT_DELAY)
previous, current = get_content_quads_with(delay: delay)
previous, current = content_quads_with(delay: delay)
previous == current
end

Expand Down Expand Up @@ -187,32 +187,32 @@ def find_position(x: nil, y: nil, position: :top)
points = wait_for_stop_moving.map { |q| to_points(q) }.first
get_position(points, x, y, position)
rescue CoordinatesNotFoundError
x, y = get_bounding_rect_coordinates
x, y = bounding_rect_coordinates
raise if x.zero? && y.zero?

[x, y]
end

private

def get_bounding_rect_coordinates
def bounding_rect_coordinates
evaluate <<~JS
[this.getBoundingClientRect().left + window.pageXOffset + (this.offsetWidth / 2),
this.getBoundingClientRect().top + window.pageYOffset + (this.offsetHeight / 2)]
JS
end

def get_content_quads
def content_quads
quads = page.command("DOM.getContentQuads", nodeId: node_id)["quads"]
raise CoordinatesNotFoundError, "Node is either not visible or not an HTMLElement" if quads.size.zero?

quads
end

def get_content_quads_with(delay: MOVING_WAIT_DELAY)
previous = get_content_quads
def content_quads_with(delay: MOVING_WAIT_DELAY)
previous = content_quads
sleep(delay)
current = get_content_quads
current = content_quads
[previous, current]
end

Expand All @@ -224,9 +224,9 @@ def get_position(points, offset_x, offset_y, position)
x = point[:x] + offset_x.to_i
y = point[:y] + offset_y.to_i
else
x, y = points.inject([0, 0]) do |memo, point|
[memo[0] + point[:x],
memo[1] + point[:y]]
x, y = points.inject([0, 0]) do |memo, coordinate|
[memo[0] + coordinate[:x],
memo[1] + coordinate[:y]]
end

x /= 4
Expand Down
21 changes: 10 additions & 11 deletions lib/ferrum/page.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def reset

extend Forwardable
delegate %i[at_css at_xpath css xpath
current_url current_title url title body doctype set_content
current_url current_title url title body doctype content=
execution_id evaluate evaluate_on evaluate_async execute evaluate_func
add_script_tag add_style_tag] => :main_frame

Expand Down Expand Up @@ -153,8 +153,7 @@ def wait_for_reload(sec = 1)
@event.set
end

def bypass_csp(value = true)
enabled = !value.nil?
def bypass_csp(enabled: true)
command("Page.setBypassCSP", enabled: enabled)
enabled
end
Expand Down Expand Up @@ -274,14 +273,14 @@ def prepare_page
resize(width: width, height: height)

response = command("Page.getNavigationHistory")
if response.dig("entries", 0, "transitionType") != "typed"
# If we create page by clicking links, submitting forms and so on it
# opens a new window for which `frameStoppedLoading` event never
# occurs and thus search for nodes cannot be completed. Here we check
# the history and if the transitionType for example `link` then
# content is already loaded and we can try to get the document.
get_document_id
end
return unless response.dig("entries", 0, "transitionType") != "typed"

# If we create page by clicking links, submitting forms and so on it
# opens a new window for which `frameStoppedLoading` event never
# occurs and thus search for nodes cannot be completed. Here we check
# the history and if the transitionType for example `link` then
# content is already loaded and we can try to get the document.
get_document_id
end

def inject_extensions
Expand Down
2 changes: 1 addition & 1 deletion spec/browser_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ module Ferrum
it "does not run into content quads error" do
browser.go_to("/ferrum/index")

allow_any_instance_of(Node).to receive(:get_content_quads)
allow_any_instance_of(Node).to receive(:content_quads)
.and_raise(Ferrum::CoordinatesNotFoundError,
"Could not compute content quads")

Expand Down
Loading

0 comments on commit e45da11

Please sign in to comment.