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
12345678910111213
# lists all files and folders under target/ folderDir.glob('target/**/**').selectdo|f|ifFile.directory?f# do somethingelse# do somethingendend# ONLY list all in target/ , doesn't list subfolders like target/subfolders/Dir.glob('target/**').selectdo|f|end
require'csv'CSV.open("datacfg.csv","r",{headers:true})do|csv|matches=csv.find_alldo|row|putsrow.headers[0]# first column of headerputsrow[0]# first column of each rowendend
Create a http connection to download big file and calculate progress
1234567891011121314151617181920212223
require'net/http'downloadLink="http://abc/def/ghi.zip"uri=URI.parsedownloadLinkNet::HTTP.start(uri.host,uri.port)do|http|request=Net::HTTP::Get.newuri.request_urirequest.basic_authUSERNAME,PASSWORD# if you need basic web authhttp.requestrequestdo|response|download_size=0beginfile=File.open("target.zip",'wb')length=response.content_lengthresponse.read_bodydo|fragment|download_size+=fragment.lengthfile.write(fragment)progress='%.2f'%(download_size.to_f*100/length)endensurefile.closeendendend
XML handle by nokogiri
1234567891011
require'nokogiri'doc=Nokogiri::XML(f)# create a xml doc from a filenodes=doc.xpath('//bean[@id="getcha"]/*')# find nodes under bean with id 'getcha'nodes.eachdo|node|node['value']="good"# set the attribute 'value' to 'good'node.content="bad"# set the content to 'bad'endFile.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