Skip to content

Commit

Permalink
Add recommendations for simple File IO
Browse files Browse the repository at this point in the history
In his 2016 talk ["Little Snippets"](https://youtu.be/mC9TyVeER_8?t=560) Xavier Noria (@fxn) points out that Ruby 1.8 had the idiom

```ruby
File.open(filename, 'w') do |f|
  f.write(content)
end
```

whereas starting with Ruby 1.9 this can be replaced with

```ruby
File.write(filename, content)
```

We add this suggestion for simple truncating file writes in text
and binary mode, as well as the corresponding scenaro for reading files.

The suggestions were also implemented for RuboCop:
- `File/Write`: rubocop/rubocop#10260
- `File/Read`: rubocop/rubocop#10261
  • Loading branch information
leoarnold authored and bbatsov committed Nov 22, 2021
1 parent c71dd69 commit a4aa353
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -2086,6 +2086,72 @@ rescue StandardError => e
end
----

=== Reading from a file [[file-read]]

Use the convenience methods `File.read` or `File.binread` when only reading a file start to finish in a single operation.

[source,ruby]
----
## text mode
# bad (only when reading from beginning to end - modes: 'r', 'rt', 'r+', 'r+t')
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') { |f| f.read }
File.open(filename, 'r') do |f|
f.read
end
# good
File.read(filename)
## binary mode
# bad (only when reading from beginning to end - modes: 'rb', 'r+b')
File.open(filename, 'rb').read
File.open(filename, 'rb', &:read)
File.open(filename, 'rb') { |f| f.read }
File.open(filename, 'rb') do |f|
f.read
end
# good
File.binread(filename)
----

=== Writing to a file [[file-write]]

Use the convenience methods `File.write` or `File.binwrite` when only opening a file to create / replace its content in a single operation.

[source,ruby]
----
## text mode
# bad (only truncating modes: 'w', 'wt', 'w+', 'w+t')
File.open(filename, 'w').write(content)
File.open(filename, 'w') { |f| f.write(content) }
File.open(filename, 'w') do |f|
f.write(content)
end
# good
File.write(filename, content)
## binary mode
# bad (only truncating modes: 'wb', 'w+b')
File.open(filename, 'wb').write(content)
File.open(filename, 'wb') { |f| f.write(content) }
File.open(filename, 'wb') do |f|
f.write(content)
end
# good
File.binwrite(filename, content)
----

=== Release External Resources [[release-resources]]

Release external resources obtained by your program in an `ensure` block.
Expand Down

0 comments on commit a4aa353

Please sign in to comment.