ruby:549
From: Hiroshi Takagi <gollum@h...>
Date: Sun, 31 Oct 2004 17:17:19 +0900
Subject: [ruby:549] るびまネタ: わたしのライブラリ
たかぎ@ログ解析屋%今日はおうちです。
先日の関西オープンソース2004ではいろいろとありがとうございました。
ミーハーなので、あの高橋さん、前田さんを見られただけで
満足して帰っちゃいましたが^^;
ところで、会場で話題になってた るびまの今後のネタ、という話でひとつ提案があります。
#私のライブラリ(always 'required' libs)公開、ってのどうでしょうか?
Ruby を使われている方なら、
自分の仕事分野でよく使う、自作のカスタムメソッドクラスなどを、
自分のライブラリファイルに集めておいて、スクリプトの先頭で
require 'mylib'
require 'myclasses'
とかしてる方が多いんではないかと。
わたしは、メソッドの細かいパラメータとかフォーマットを
すぐに忘れてしまうような浅いスタックの揮発性メモリしか頭脳に有しておりません。
一度、調べたことはメソッド化しておいておかないと忘れてしまいます。
(フォーマット文字列なんて、どれがなんだを入れておけないんですよね〜(恥
クラス・メソッド、インスタンス・メソッドの活用事例としても参考になるでしょうし、
カスタムで作られているクラスなどの事例がいろいろあれば、
これも、OOP を学ぶときのいい教材になるのではないかと思います。
いいだしべぇのわたしのものはこんな mylib.rb です。
私はログ解析屋なんで、
Date オブジェクト(これがあるからruby に転んだのかも)まわりのものがやたらと多い。
「先月の」「今月の」「先週の」ログを扱うために
しょっちゅう使うメソッドばっかりですが。
### working with Date object
require 'date'
def last_month
# return previous month in string form 'yyyy-mm'
today = Date.today
last_day_of_prev_month = today - today.day
last_day_of_prev_month.to_s[0, 7]
end
def last_month_start_end
# return fist day and last day of last month
today = Date.today
last_day_of_prev_month = today - today.day
first_day_of_prev_month = last_day_of_prev_month - last_day_of_prev_month.day + 1
return first_day_of_prev_month, last_day_of_prev_month
end
def this_month_start_end
# return fist day and last day of this month
today = Date.today
first_day_of_this_month = today - today.day + 1
first_day_of_next_month = first_day_of_this_month >> 1
last_day_of_this_month = first_day_of_next_month -1
return first_day_of_this_month, last_day_of_this_month
end
def sunday_of_last_week
# return "last Sunday" as Date object
today = Date.today
sunday = today - today.wday # Sunday of this week
sunday - 7 # Last Sunday
end
### working with Time object
class Time
def iso8601
self.strftime("%y-%m-%d %H:%M:%S")
end
end
def time_stamp(msg)
print "#{Time.now.iso8601} #{msg}"
end
ruby-list:39826 で中田さんに考案していただいた
以下のモジュールも重宝しているものです。
(要素がString, Fixnum 以外のカスタムオブジェクトで
配列の集合演算可能にするためのモジュール。)
module Hash::ReadyMade
def eql?(other)
self.class == other.class and
(sv = instance_variables).size == (ov = other.instance_variables).size and
sv.all? do |v| ov.include?(v) and
instance_variable_get(v).eql?(other.instance_variable_get(v))
end
end
def hash
instance_variables.inject(self.class.hash) {|h, v|
h ^ instance_variable_get(v).hash
}
end
end
Ruby っぽくないスクリプトをいっぱい並べ立ててすみません^^
ではでは、また。
--
Hiroshi Takagi <gollum@h...>
--
ML: ruby@m...
使い方: http://QuickML.com/