Masatoshi Nishiguchi

Ruby file operations

Currently working directory

puts "Dir.pwd: #{Dir.pwd}"

Join path

FILE_DIR = "#{Dir.pwd}/test/fixtures/files"
filename = "example.xml"
path     = File.join(FILE_DIR, filename)

Read

contents = File.open("sample.txt", "r") { |file| file.read }
puts contents
file = File.read(path)

Reading multiple files

def read_all_feed_files
  pattern   = File.join(Dir.pwd, "test", "fixtures", "files", "feed_*.xml")
  filenames = Dir.glob(pattern)

  [].tap do |xml_files|
    filenames.each do |io|
      xml_files << File.read(io)
    end
  end
end

Reading each line

File.open("example.rb", "r") do |io|  
  io.each_line do |line|
    puts line
  end
end  

Reading from URL

require "open-uri"
puts open("https://mnishiguchi.com").read

Reading JSON

data = File.read("#{Rails.root}/test/fixtures/files/feed_a.json")
JSON.parse(data.encode("ASCII", { undef: :replace, replace: "" }))

Write

File.open("data_file.yml", "w") do |io|
  io.write(data)
end
File.write "data_file.yml", data

Rake tasks basics

Basic commands

# List all the tasks
bundle exec rake -T

Rake tasks in Rails

be rake db:migrate:redo
be rake log:clear
be rake db:migrate db:seed log:clear
# List all the TODOs and FIXMEs
be rake notes
be rake rails:update  # Rails 4
be rake app:update    # Rails 5
# d - diff
# Y - yes
# n - no
# q - quit

first_or_create! in db/seed.rb

This allows us to run the be rake db:seed command without deleting any data.

# db/seed.rb
Post.where(
  title: "The title",
  body:  "Hello world"
).first_or_create!

Write custom tasks

# Rakefile
namespace :masatoshi do
  desc "Say hello"
  task :hello do
    puts "Hello"
  end

  desc "Say world"
  task :world do
    puts "World"
  end

  desc "Say hello and world"
  task :hello_world => [:hello, :world]

  desc "Take parameter"
  task :custom_hello, [:name] do |t, args|
    puts "Hello, #{args[:name]}!"
  end
end

Calling tasks from a terminal

$ be rake masatoshi:hello
Hello
$ be rake masatoshi:world
World
$ be rake masatoshi:hello_world
Hello
World

Calling tasks from a ruby file

# rake_include.rb
require "rubygems"
require "bundler"
require "rake"

Bundler.require
load "Rakefile"
Rake::Task["masatoshi:custom_hello"].invoke("Mr. Nishiguchi")
ruby rake_include.rb
Hello, Mr. Nishiguchi!

Resources