using jQuery in Rails

投稿者 okkez 2010-02-20 02:00:00 GMT

最近 Rails で作っているウェブアプリケーションでは jQuery を使うようにしている。 なんとなくこうすれば良さそう、というのがわかってきたので書いておく。

google の jsapi を使う。 どこかのブログで見つけたコード片をちょっと変更したやつ。

module ApplicationHelper

  def google_jsapi_tag
    '<script type="text/javascript" src="http://www.google.com/jsapi"></script>'
  end

  def google_load_tag(name, version)
    %Q|<script type="text/javascript">google.load("#{name}", "#{version}");</script>|
  end

end

layout では以下のようにする。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
  <head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    <meta http-equiv="Content-Script-Type" content="text/javascript" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
    <%= google_jsapi_tag %>
    <%= google_load_tag 'jquery', '1.3' %>
    <%= google_load_tag 'jqueryui', '1.7' %>
    <%= javascript_include_tag 'application' %>
    <%= yield :head %>
    <%- javascript_tag do -%>
      jQuery(function($){
        if (navigator.cookieEnabled) {
          $("#cookie_check").hide();
        } else {
          $("#cookie_check").show();
        }
        <%= yield :script %>
      });
    <%- end -%>
    <%= stylesheet_link_tag 'application' %>
    <%= stylesheet_link_tag 'jquery-ui-1.7.2.custom' %>
    <title><%= @title %></title>
  </head>
  <body>
    <!-- 略 -->
  </body>
</html>

こうしておくと view では以下のように書くことができる。

<%- content_for :script do -%>
$("a#hoge").click(function(event){ /* なんか処理 */});
<%- end -%>

global な名前空間を汚さないし、割と短く書けるし気に入っている。

カテゴリ ,  | タグ , , ,  | コメントなし | トラックバックなし

コメント

トラックバック

トラックバックリンク:
http://typo.okkez.net/trackbacks?article_id=273

コメントは許可されていません