Ruby IO quick tips



Ruby IO quick tips

0 1


ruby-io-quick-tips


On Github mauricio / ruby-io-quick-tips

Ruby IO quick tips

Maurício Linhares / @mauriciojr

Use temporary directories instead of temp files

						require 'tmpdir'

Dir.mktmpdir("my-prefix") do |dir|
  File.open(File.join(dir,"text.txt"), 'w') do |f|
    f.write("this is a test")
  end
end
					

Can you fit your files in memory? Use the one liners

						IO.write("/path/to/file.txt", "This is my cool text I need to write! Yay!")
contents = IO.read("/path/to/file.txt")
					

Tempfile needs to be closed and unlinked when you're done

If you forget to do this you will have to wait until the GC runs or your process goes away.

						file = Tempfile.new
## do stuff and not close/unlink, leaked!
					

Prefer StringIO to Tempfile

StringIO does everything Tempfile does other than having a path but does not require unlinking, closing or any cleanup.

It's just winning all over the place.

Use File.join when appending paths

						path = File.join("Users", "mauricio", "projects", "ruby")
					

Is not the same as:

						path = ["Users", "mauricio", "projects", "ruby"].join(File::SEPARATOR)
					

Accessing relative files inside your project/gem

- root
  - lib
    - my_gem
      - operation.rb
  - config
    - items.yml
					

Accessing relative files inside your project/gem

						my_gem_directory = File.dir(__FILE__) # or __dir__ if you're on Ruby 2.x
File.join(my_gem_directory, "..", "..", "config", "items.yml")
					

Don't do this!

						file = File.open("some-file.ext", "w")
file.write("hey, this is bad!")
file.write("where's the exception handling code?")
file.close
					

Do this!

						File.open("some-file.txt", "w") do |f|
  f.write("this is some text\n")
  f.write("and some more text")
end
					

Use Pathname

						require 'pathname'
path = Pathname.new("README.markdown")

puts path.extname
=> ".markdown"

full_path = path.expand_path
=> Pathname:/Users/mauricio/projects/ruby/mauricio.github.com/README.markdown

puts full_path.dirname
=> Pathname:/Users/mauricio/projects/ruby/mauricio.github.com
					

THE END

By Maurício Linhares / made with reveal.js

Ruby IO quick tips Maurício Linhares / @mauriciojr