2015年5月21日木曜日

【Ruby On Rails】Stringなど既存のクラスにメソッドを追加する方法

いつも忘れるのでメモ。

このアプリケーションだけで頻繁に使う処理をStringなど既存のrubyクラスに足したいときがある。
たとえばStringに 文字列を大文字・小文字が相互に続くように変換する dekoboko というメソッドを足すとする。

core_ext/string.rb というファイルを作ってそこでStringクラスを追記する。

X
# coding:utf-8

class String

def dekoboko
ret = ""
self.length.times do | idx |
if idx % 2 == 0
ret += self[ idx ].upcase
else
ret += self[ idx ].downcase
end
end
ret
end

end



application.rbでstring.rbをloadすればStringクラスを拡張できる。


module MyApp
class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras ) # 基本クラスの拡張を読み込む Dir[ config.root.join( "core_ext/*.rb" ) ].each do | f | load f end


コンソールから実行すると、
irb(main):001:0> "abcdefg".dekoboko
=> "AbCdEfG"

メソッドが追加できている!

0 件のコメント:

コメントを投稿