プラグインで Rails のコア機能を書き換える(HowToWritePluginToModifyRailsCore)
【ma2注】以下のURLの翻訳。
http://wiki.rubyonrails.com/rails/pages/HowToWritePluginToModifyRailsCore
プラグインは最後にロードされるため,Railsのコア機能のほとんどをプラグインを使って変更できる。
以下に Rails のバリデーションエラーメッセージを変えるだけの単純な例を示す。active_record/validations.rb を見るとオリジナルのメッセージが分かる。
■ ステップ1
# ruby script/generate plugin new_errors
これは new_errors というディレクトリを vendor/plugins の下に作る。
■ ステップ2
init.rb の中に以下の行を追加する。
require 'new_errors'
■ ステップ3
lib/new_errors/rb にコードを追加する。
module ActiveRecord class Errors @@default_error_messages[:inclusion] = "is not included in the list ignoramus." @@default_error_messages[:exclusion] = "is reserved. Pay attention!" @@default_error_messages[:invalid] = "is invalid, moron." @@default_error_messages[:confirmation] = "doesn't match confirmation. Pick something that does!" @@default_error_messages[:accepted ] = "must be accepted or it will not work." @@default_error_messages[:empty] = "can't be empty like your bank account" @@default_error_messages[:blank] = "can't be blank like your brain." @@default_error_messages[:too_long] = "is too long (max is %d characters). IT IS TOO LONG!!!" @@default_error_messages[:too_short] = "is too short (min is %d characters). t.o.o.s.h.o.r.t." @@default_error_messages[:wrong_length] = "is the wrong length (should be %d characters). I'm sorry. That is an incorrect response." @@default_error_messages[:taken] = "has already been taken by your mom." @@default_error_messages[:not_a_number] = "is not a number. Numbers are things like 01234 ok?" end end