text stringlengths 0 444 |
|---|
end |
# good |
File.binwrite(filename, content) |
---- |
=== Release External Resources [[release-resources]] |
Release external resources obtained by your program in an `ensure` block. |
[source,ruby] |
---- |
f = File.open('testfile') |
begin |
# .. process |
rescue |
# .. handle error |
ensure |
f.close if f |
end |
---- |
=== Auto-release External Resources [[auto-release-resources]] |
Use versions of resource obtaining methods that do automatic resource cleanup when possible. |
[source,ruby] |
---- |
# bad - you need to close the file descriptor explicitly |
f = File.open('testfile') |
# some action on the file |
f.close |
# good - the file descriptor is closed automatically |
File.open('testfile') do |f| |
# some action on the file |
end |
---- |
=== Atomic File Operations [[atomic-file-operations]] |
When doing file operations after confirming the existence check of a file, frequent parallel file operations may cause problems that are difficult to reproduce. |
Therefore, it is preferable to use atomic file operations. |
[source,ruby] |
---- |
# bad - race condition with another process may result in an error in `mkdir` |
unless Dir.exist?(path) |
FileUtils.mkdir(path) |
end |
# good - atomic and idempotent creation |
FileUtils.mkdir_p(path) |
# bad - race condition with another process may result in an error in `remove` |
if File.exist?(path) |
FileUtils.remove(path) |
end |
# good - atomic and idempotent removal |
FileUtils.rm_f(path) |
---- |
=== Standard Exceptions [[standard-exceptions]] |
Prefer the use of exceptions from the standard library over introducing new exception classes. |
== Assignment & Comparison |
=== Parallel Assignment [[parallel-assignment]] |
Avoid the use of parallel assignment for defining variables. |
Parallel assignment is allowed when it is the return of a method call, used with the splat operator, or when used to swap variable assignment. |
Parallel assignment is less readable than separate assignment. |
[source,ruby] |
---- |
# bad |
a, b, c, d = 'foo', 'bar', 'baz', 'foobar' |
# good |
a = 'foo' |
b = 'bar' |
c = 'baz' |
d = 'foobar' |
# good - swapping variable assignment |
# Swapping variable assignment is a special case because it will allow you to |
# swap the values that are assigned to each variable. |
a = 'foo' |
b = 'bar' |
a, b = b, a |
puts a # => 'bar' |
puts b # => 'foo' |
# good - method return |
def multi_return |
[1, 2] |
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.