• 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

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 genki on Sat 5 Jan 2008 at 16:49 with 0 comments