概要
オープンクラスで既存ライブラリを拡張し、config/initializerに配置する
内容
オープンクラスで既存ライブラリを拡張し、config/initializerに配置することで、
起動後に各処理から利用可能にします。
サンプル
Timeクラスを拡張してミリ秒単位の時間(数値・文字列)の取得メソッドを追加します。
config/initializer/time.rb
class Time # get current time(msec # @return current time(msec) def self.now_msec self.now.instance_eval { self.to_i * 1000 + (usec/1000) } end # get msec format string "%Y/%m/%d %H:%M:%S.%L" # @return msec format string "%Y/%m/%d %H:%M:%S.%L" def self.now_msec_format self.now.strftime("%Y/%m/%d %H:%M:%S.%L") end end
controller
hoge_controller.rb
class HogeController < ApplicationController skip_before_filter :authorize def index @time = Time.now_msec @time_format = Time.now_msec_format end end
出力
time= 1374675245146 time_format= 2013/07/24 23:14:05.146