Useful Methods in Ruby

This week i write automatic utility tools for colleague. It saves time and reduce trivial works. Learn useful ruby built-in methods.

List all under a folder

1
2
3
4
5
6
7
8
9
10
11
12
13
# lists all files and folders under target/ folder
Dir.glob('target/**/**').select do |f|
  if File.directory? f
    # do something
  else
    # do something
  end
end

# ONLY list all in target/ , doesn't list subfolders like target/subfolders/
Dir.glob('target/**').select do |f|

end

Get folder name or file name from file path

1
2
3
f = "/abc/def/ghi.rb"
File.dirname(f) # /abc/def
File.basename(f) # ghi.rb

Read and parse file to json

@data will be JSON object

1
2
3
require 'json'

File.open("data.cfg", "r:UTF-8") { |f| @data = JSON.parse(f.read) }

Write json to file

Use JSON.pretty_generate to create well format json file.

1
2
3
require 'json'

File.open("data.cfg", "w") {|file| file.puts JSON.pretty_generate(@data)}

Read a CSV file

{ headers: true } means first row is as header

1
2
3
4
5
6
7
8
require 'csv'

CSV.open("datacfg.csv", "r", { headers: true }) do |csv|
  matches = csv.find_all do |row|
    puts row.headers[0] # first column of header
    puts row[0] # first column of each row
  end
end

Create a http connection to download big file and calculate progress

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
require 'net/http'

downloadLink = "http://abc/def/ghi.zip"
uri = URI.parse downloadLink
Net::HTTP.start(uri.host, uri.port) do |http|
  request = Net::HTTP::Get.new uri.request_uri
  request.basic_auth USERNAME, PASSWORD # if you need basic web auth

  http.request request do |response|
    download_size = 0
    begin
      file = File.open("target.zip", 'wb')
      length = response.content_length
      response.read_body do |fragment|
        download_size += fragment.length
        file.write(fragment)
        progress = '%.2f' % (download_size.to_f * 100 / length)
      end
    ensure
      file.close
    end
  end
end

XML handle by nokogiri

1
2
3
4
5
6
7
8
9
10
11
require 'nokogiri'

doc = Nokogiri::XML(f) # create a xml doc from a file

nodes = doc.xpath('//bean[@id="getcha"]/*') # find nodes under bean with id 'getcha'
nodes.each do |node|
  node['value'] = "good" # set the attribute 'value' to 'good'
  node.content = "bad" # set the content to 'bad'
end

File.open(f, 'w') { |file| file.write(doc) } # write xml to file

xpath with xml namespace

For example, the bean is under namespace http://www.springframework.org/schema/util

1
nodes = doc.xpath('//util:bean[@id="getcha"]/*', {"util" => "http://www.springframework.org/schema/util"} )

Comments