RJSでメソッドを共有したいときは、helperを使おう

休憩中に超速メモ。helperに定義したメソッドは、RJSテンプレート内でpageにバインドされている。どういうことかというと、

# helpers/comments_helper.rb
module CommentsHelper
  def show_comments
    page["comments"].replace_html :partial => "comments"
  end
end

のようにしておくと、

# views/comments/show.js.rjs
page.show_comments

が使える。

例えば、コメントの追加時とコメントの表示時に「コメントの表示」という共通の処理をしたいときに役に立つ。