class RuboCop::Cop::Style::FileRead
Favor ‘File.(bin)read` convenience methods.
@example
# bad - text mode File.open(filename).read File.open(filename, &:read) File.open(filename) { |f| f.read } File.open(filename) do |f| f.read end File.open(filename, 'r').read File.open(filename, 'r', &:read) File.open(filename, 'r') do |f| f.read end # good File.read(filename) # bad - binary mode File.open(filename, 'rb').read File.open(filename, 'rb', &:read) File.open(filename, 'rb') do |f| f.read end # good File.binread(filename)
Constants
- MSG
- READ_FILE_START_TO_FINISH_MODES
- RESTRICT_ON_SEND
Public Instance Methods
on_send(node)
click to toggle source
# File lib/rubocop/cop/style/file_read.rb, line 66 def on_send(node) evidence(node) do |filename, mode, read_node| message = format(MSG, read_method: read_method(mode)) add_offense(read_node, message: message) do |corrector| range = range_between(node.loc.selector.begin_pos, read_node.source_range.end_pos) replacement = "#{read_method(mode)}(#{filename.source})" corrector.replace(range, replacement) end end end
Private Instance Methods
evidence(node) { |filename, first || 'r', read_node| ... }
click to toggle source
# File lib/rubocop/cop/style/file_read.rb, line 81 def evidence(node) file_open?(node) do |filename, mode_array, block_pass| read_node?(node, block_pass) do |read_node| yield(filename, mode_array.first || 'r', read_node) end end end
file_open_read?(node)
click to toggle source
# File lib/rubocop/cop/style/file_read.rb, line 97 def file_open_read?(node) return true if send_read?(node) block_read?(node) end
read_method(mode)
click to toggle source
# File lib/rubocop/cop/style/file_read.rb, line 103 def read_method(mode) mode.end_with?('b') ? :binread : :read end
read_node?(node, block_pass) { |node| ... }
click to toggle source
# File lib/rubocop/cop/style/file_read.rb, line 89 def read_node?(node, block_pass) if block_pass.any? yield(node) elsif file_open_read?(node.parent) yield(node.parent) end end