月曜日, 9月 06, 2010

Exerb(Rubyスクリプトをexeファイルに)

2007/01/16perlfreak.vox.comより転載)

RubyスクリプトをWindowsのexeファイルにしてくれるExerbなるものがある。
まず、Cygwin環境でインストール。

$ unzip exerb-4.1.0.zip
$ cd exerb-4.1.0
$ ruby setup.rb

以下は、CSVファイルの行を指定された項目でソートし、項目の入れ替えを行なうサンプル。
ファイルは、convert.rb、sort-array.rb、convert.confの3つ。

=== (convert.rb ここから) ===
#!/usr/bin/ruby

require "csv"
require "sort-array"

print "Now working..."

array_file = ARGV

if array_file

array_file.each do |file_name|

if FileTest.size?(file_name) && /(.*)\.csv$/i =~ file_name
to_file = $1 + '_new.csv'
array_input = Array.new

CSV.open(file_name, 'rb') do |row|
array_input <<>

array_output = SortArray.new.convert(array_input)

File.open(to_file, 'wb') do |output|

array_output.each do |array_line|
line = ""

array_line.each do |item|

if line.size == 0
line = item
else
line = line + ',' + item
end
end

line = line + "\r\n"
output.write(line)
end
end
end
end
end

exit
=== (convert.rb ここまで) ===

=== (sort-array.rb ここから) ===
class SortArray
# 設定ファイルの内容を取得してハッシュで返す
def get_conf
conf_file = "convert.conf"
hash_conf = Hash.new

if defined? ExerbRuntime
conf_file = File.dirname(ExerbRuntime.filepath) + "/" + conf_file
end

File.readlines(conf_file).each do |line|
line = line.sub(/(?:\r|\r\n|\n)\z/, "")

if /\a\s*(.*)\s*:\s*(.*)\s*\z/ =~ line
hash_conf["$1"] = "$2"
end
end

return hash_conf
end

# 引数の配列の要素を設定によって並べ替えて返す
def convert(array_input)
@array_input = array_input
hash_conf = self.get_conf
array_keys = Array.new
array_result = Array.new

hash_conf.each do |key,value|
if key == "sort_key"
array_keys = value.split(/\s*,\s*/)
end
end

array_result = @array_input.sort{|y,x| \
[x[array_keys[0].to_i],x[array_keys[1].to_i],x[array_keys[2].to_i]] \
<=> [y[array_keys[0].to_i],y[array_keys[1].to_i],y[array_keys[2].to_i]]}

array_result.each do |line_item|
line_item[1],line_item[2],line_item[3],line_item[4],line_item[5] \
= line_item[3],line_item[5],line_item[1],line_item[2],line_item[4]
end

return array_result
end
end
=== (sort-array.rb ここまで) ===

=== (convert.conf ここから) ===
sort_key:0,3,5
=== (convert.conf ここまで) ===

これらの準備ができたところで

$ mkexy convert.rb
$ exerb convert.exy

はい、これでconvert.exeのできあがり。
Windows上でconvert.exeに6項目以上からなるCSVファイルをドラッグ&ドロップすると、拡張子の前に_newがついた変換後のファイルが生成される。

0 件のコメント: