5th Sat
How To Use Conditional RJS
RJSテンプレートは、RubyコードからJavaScriptコードを生成
するための仕組みです。
今回は、RJSテンプレートの中でJavaScriptの条件分岐を
簡潔に記述するために、PrototypeHelperを拡張する方法を紹介します。
以下のようなファイルを作成して、config/initializersの下に
設置します(Rails 2.0以降の場合)
prototype_helper_ext.rb
rails>>
module ActionView
module Helpers
module PrototypeHelper
class JavaScriptGenerator
def if(condition, &block)
page << "if(#{condition}){"
block.call if block
page << '}'
end
def elsif(condition, &block)
page << "else if(#{condition}){"
block.call if block
page << '}'
end
def else(&block)
page << "else{"
block.call if block
page << '}'
end
end
end
end
end
<<--
これによって、こんな感じに条件分岐を記述できるようになります。
rails>>
render :update do |page|
page.if "$$('#posts .post').length == 0" do
page.remove 'posts'
end
end
<<--
最初から用意されててもいい気がする。
posted by
genki on Sat 5 Jan 2008 at 16:49 with 0 comments