Ruby

Basic

Get the path of script.

p __dir__

Get current directory.

p Dir.pwd

Escape html.

require "cgi/util"

CGI.escape_html("< > & \"") # => "&lt; &gt; &amp; &quot;"

Main block(which will be called only if you run this file).

if __FILE__ == $0
  # code
end

File

Write and read from file.

File.write('foo.txt','hello')
# => 5
File.read('foo.txt')
# => "hello"

Read file(for larger file).

File.foreach('foo.txt') do |line|
  puts line
end

Read as CSV.

require 'csv'

CSV.foreach("foo.csv",encoding:"cp932",col_sep:"\t") do |row|
  puts row
end

Get disk space via df command(without installing any gems).

def df(pat) # i.e. /dev/vda3
  res = `df -h | grep #{pat}`.strip
  res.split(/ +/)[1,4] # ["14G", "4.6G", "8.8G", "35%"]
end

Read and write JSON.

require 'json'

data = JSON.parse(File.read("foo.json"))
File.write("bar.json",JSON.pretty_generate(data))

Database

Mysql

To activate load data local .. on MySQL8.0, need to set local_infile: true.

client = Mysql2::Client.new(host: "localhost", username: "user", local_infile: true)
client.query("use db")
results = client.query("select * from t")
results.each do |row|
  puts row
end
client.close

Time(date)

Get current time.

Time.now.strftime("%F %T")
# => "2022-01-29 21:14:09"

Optparse

require 'optparse'

e = false # flag for execution
options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: foo.rb [-a foo] [-b bar] [-e]"
  opts.on("-a", "--apple foo", "Foo") { |v| options[:a] = v }
  opts.on("-b", "--banana bar", "Bar") { |v| options[:b] = v }
  opts.on("-e", "--execute", "Execute all commands.") { |v| e = true }
end.parse!

Geo3x3

require './geo_3x3'

lat, lng = 31.908714674017606, 131.42030837301505
level = 18
puts "#{lat},#{lng}"
geo = Geo3x3.encode(lat,lng,level)
puts geo
p Geo3x3.decode(geo)

Prawn(PDF)

require 'prawn'

pdf = Prawn::Document.new

ipamp_path = "./ipamp.ttf"
pdf.font_families.update("ipamp" => {normal: ipamp_path,
                            bold: ipamp_path,
                            italic: ipamp_path,
                            bold_italic: ipamp_path})

ipaexg_path = "./ipaexg.ttf"
pdf.font_families.update("ipaexg" => {normal: ipaexg_path,
                            bold: ipaexg_path,
                            italic: ipaexg_path,
                            bold_italic: ipaexg_path})


pdf.font_families.update("noto-serif" => {normal: "./NotoSerifJP-Regular.otf",
                            bold: "./NotoSerifJP-Bold.otf",
                            italic: "./NotoSerifJP-Regular.otf",
                            bold_italic: "./NotoSerifJP-Regular.otf"})                            

pdf.font "ipamp"
pdf.text "Prawnで日本語出力。IPA明朝"
pdf.formatted_text [{text: "ボールド", styles: [:bold]}, {text: "イタリック", styles: [:italic]}]

pdf.font "ipaexg"
pdf.text "Prawnで日本語出力。IPAゴシック"
pdf.formatted_text [{text: "ボールド", styles: [:bold]}, {text: "イタリック", styles: [:italic]}]

pdf.font "noto-serif" # Not working with prawn 2.4.0
pdf.text "Prawnで日本語出力。Noto Serif JP"
pdf.formatted_text [{text: "ボールド", styles: [:bold]}, {text: "イタリック", styles: [:italic]}]

pdf.font "Helvetica" # Courier, Times-Roman are also available
pdf.text "Prawn with embedded font. Helvetica"
pdf.formatted_text [{text: "bold", styles: [:bold]}, {text: "italic", styles: [:italic]}]

pdf.render_file "hello.pdf"

prawn-pdf