RJSテンプレートは、RubyコードからJavaScriptコードを生成 するための仕組みです。 今回は、RJSテンプレートの中でJavaScriptの条件分岐を 簡潔に記述するために、PrototypeHelperを拡張する方法を紹介します。

以下のようなファイルを作成して、config/initializersの下に 設置します(Rails 2.0以降の場合)

prototype_helper_ext.rb

   1  module ActionView
   2    module Helpers
   3      module PrototypeHelper
   4        class JavaScriptGenerator
   5          def if(condition, &block)
   6            page << "if(#{condition}){"
   7            block.call if block
   8            page << '}'
   9          end
  10  
  11          def elsif(condition, &block)
  12            page << "else if(#{condition}){"
  13            block.call if block
  14            page << '}'
  15          end
  16  
  17          def else(&block)
  18            page << "else{"
  19            block.call if block
  20            page << '}'
  21          end
  22        end
  23      end
  24    end
  25  end

これによって、こんな感じに条件分岐を記述できるようになります。

   1  render :update do |page|
   2    page.if "$$('#posts .post').length == 0" do
   3      page.remove 'posts'
   4    end
   5  end

最初から用意されててもいい気がする。

posted by Png genki on Sat 5 Jan 2008 at 16:49
Contents
How To Use Conditional RJS
Comments
瀧内元気: MacOS版は以下にあります * [genki/ViMouse](https://githu... '23-1
dsjf: https://gist.github.com/6bf1bf2c3cbb5eb6e7a7 これ... '13-1
瀧内元気: おお、チェックしてみます。thx! '11-12
overisland: Reeder for iPhone もこの UI を実装していますね。 '11-12
瀧内元気: その情報は見たのですが、以下のサイトによると、現在はまた必要になってるっぽいんですよね。 ... '11-12
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ