メイン

Ruby アーカイブ

2006年01月13日

Ruby on Rails で Ajax

Ruby on RailsでAjaxを使ってみた。
RoRにはAjaxを使うためのヘルパーメソッドがあるみたい。
その中の代表例が

1.javascript_include_tag
<%= javascript_include_tag "prototype" %>によりprototype.jsライブラリをインポートします。つまり、
<script src="/javascripts/prototype.js" type="text/javascript"></script>こんな感じになります。

2.link_to_remote
link_to_remote(name, options = {}, html_options = {})
link_toメソッドをAjax風に仕立てたものみたいで、
nameパラメータが表示される文字列
optionsパラメータがDOM のエレメントの id 属性。ここで指定されるid属性の中身がアクションの結果により置き換わる
html_optionsパラメータがアクションURL
ということで、

<%= link_to_remote( "click here",
:update => "time_div",
:url =>{ :action => :ajaxtest_say_when }) %>
と書けば、ajaxtest_say_whenアクションによって<div id="time_div></div>で囲まれた中身が置き換わります。
ということで、以前作ったBlogコントローラに
class BlogController < ApplicationController
 def index
 end
 def ajaxtest_say_when
  render_text "<p>current time is " + DateTime.now.to_s + " from ajaxtest_say_when</p>"
 end
end

と書いて、Viewのindex.rhtmlに
<html>
 <head>
  <%= javascript_include_tag "prototype" %>
 </head>
 <body>
  <div id="time_div">
   current time is
   <%= link_to_remote( "click here",
    :update => "time_div",
    :url =>{ :action => :ajaxtest_say_when }) %>
  </div>
 </body>
</html>

と書けばできあがる。
まぁ、簡単。

2006年01月30日

パスワードをハッシュしDB登録 : RoR

ユーザー登録ページとログインページを作る

まずは、ログイン用のコントローラを作る

ruby script\generate controller Login add_user delete_user list_users login logout

ユーザー登録ページを作るには、まず、view/login/add_user.rhtmlを編集し、ビューを構築する。

<% @page_title = "Add a User" -%>
<%= error_messages_for 'author' %>
<%= form_tag %>
<table>
  <tr>
   <td>User name</td>
   <td><%= text_field("author", "name") %></td>
  </tr>
  <tr>
   <td>Password</td>
   <td><%= password_field("author", "password") %></td>
  </tr>
  <tr>
   <td></td>
   <td><input type="submit" value=" ADD USER " /></td>
  </tr>
</table>
<%= end_form_tag %>

次に先ほど自動生成されたLoginコントローラをいじってみる。

class LoginController < ApplicationController
  def add_user
   if request.get?
    @author = Author.new
   else
    @author = Author.new(params[:author])
    if @author.save
     flash[:notice] = "Author #{@author.name} created"
     redirect_to(:action => "index")
   end
   end
  end
end

@author = Author.new(@params[:author])でpostされたデータを基にAuthorのインスタンスを生成し、@author.saveで保存(DB保存)する。
このときにパスワードをハッシュ値化する場合は、ActiveRecordのCallbackを使う。
Callbackのうち、before_createというメソッドが、createの直前に呼ばれる。
あとは、Digest::Baseでハッシュ化というわけ。
といことで、class Author < ActiveRecord::Baseに
def before_create
 self.password = Digest::MD5.hexdigest(self.password)
end

を加えれば、ハッシュ値化されたパスワードが保存される。

次にログインでは、ログインコントローラに

def login
 if request.get?
  session[:user_id] = nil
  @author = Author.new
 else
  @author = Author.new(params[:author])
  logged_in_user = @author.try_to_login
  if logged_in_user
   #ログイン後画面へ
  else
   #エラー画面へ
  end
 end
end

Authorモデルクラスに

def try_to_login
 self.password = Digest::MD5.hexdigest(self.password)
 begin
  Author.find(:first, :conditions => ["name = ? and password = ?", self.name, self.password])
 rescue
  return nil
 end
end

を追加する。

2006年02月02日

RSS出力 : RoR

Ruby on Rails勉強中。
エントリを投稿したらRSSを出力するようにしてみた。
果たしてこのやり方がRailsっぽいのかわからないので、かしこい人トラックバックしてください。

1.RSS生成クラスをhelpersに入れてみた。
rss_writer.rb

require 'rss/2.0'
require 'rss/maker'
class RssWriter
  def output(entries)
   rss = RSS::Maker.make('1.0') do |maker|
    maker.channel.about = 'http://localhost:3000/index.rdf';
    maker.channel.title = 'My RSS';
    maker.channel.description = 'My description';
    maker.channel.link = 'http://localhost:3000/blog';
    entries.each do |entry|
     item = maker.items.new_item;
     item.link = 'http://localhost:3000/entry/show/' + entry.id.to_s;
     item.title = entry.title;
     item.description = entry.text;
     item.date = Time.now;
    end
   end
   f = open("public/index.xml", "w")
   f.puts(rss.to_s)
   f.close()
  end
end

2.Entryモデルクラスのafter_saveコールバックを編集
entry.rb

require 'app/helpers/rss_writer'
class Entry < ActiveRecord::Base
 def after_save
  entries = Entry.find(省略)
  writer = RssWriter.new
  writer.output(entries)
 end
end

ActionController

Filters

コントローラ内でCGIのリクエスト・レスポンスに対する前処理・後処理を行うのが Filter 機能です。ユーザ認証、共通の前処理、文字コード変換などの用途に適しています。前処理の場合は before_filter、後処理の場合は after_filter を用い、処理の内容はメソッド・ブロック・クラスの3種類のいずれかで定義します。

例えば、どのページを開こうとしても、必ずログインページにリダイレクトするようなものを書きたい場合に便利みたいです。
ApplicationControllerにFilterの条件を記述し、
class ApplicationController < ActionController::Base
  def authorize
   unless なんらかの条件
    flash[:notice] = "Please log in"
    redirect_to(:controller => "login", :action => "login")
   end
  end
end

とかして、各アクションコントローラに
before_filter :authorize

と追加する。そうすると、各コントローラ内でのCGIリクエスト処理前にApplicationControllerのauthorizeが呼ばれる。そこで、「なんらかの条件」、ログインの場合は、sessionなんかを調べて、なければlogin画面にリダイレクトするようになります。
ただし、loginアクションでもfilterされてしまったら、延々とリダイレクトしてしまうことになるので、:exceptしておく。
before_filter :authorize, :except => :login

2006年02月08日

FCKEditorをRuby on Railsで使う

FCKEditorというWYSIWYGエディタをRuby on Railsアプリ上で使う方法

1.FCKEditorをダウンロード
http://www.fckeditor.netから最新版のFCKEditorをダウンロードし、展開します。
展開したファイル及びフォルダのうち、下記のものをpublic/javascriptsフォルダにコピーします。

/editor/
fckconfig.js
fckeditor.js
fckstyles.xml
fcktemplates.xml

2.fckeditor.jsの編集
fckeditor.jsファイルを開き、this.BasePathを'/javascripts/'に書き換える

// FCKeditor Class
var FCKeditor = function( instanceName, width, height, toolbarSet, value )
{
// Properties
this.InstanceName = instanceName ;
this.Width = width || '100%' ;
this.Height = height || '200' ;
this.ToolbarSet = toolbarSet || 'Default' ;
this.Value = value || '' ;
this.BasePath = '/javascripts/' ;
this.CheckBrowser = true ;
this.DisplayErrors = true ;

3.fckeditor.jsをインクルードする
headタグ内にjavascript_include_tagを使いfckeditor.jsをインクルードします。

<%= javascript_include_tag "fckeditor" %>

4.テキストエリアを置く
テキストエリアは、今までと同じようにActiveViewのtext_areaで配置します。

<%= text_area("object", "method") %>

5.javascriptでテキストエリアをFCKEditorに置き換える

<script type="text/javascript">
window.onload = function()
{
var oFCKeditor = new FCKeditor( 'MyTextarea' ) ;
oFCKeditor.ReplaceTextarea() ;
}
</script>

というのは、こちらを引用しました。

2006年02月09日

select :multiple : RoR

Ruby on Railsのこねた

<% select(object, method, choices, options = {}, html_options = { :multiple => "" }) %>

の出力は、
<select name="object[method]" multiple="multiple">
<option value="choice_1">choice_1</option>
<option value="choice_2">choice_2</option>
....
<option value="choice_n">choice_n</option>
</select>

となり、複数選択のリストができあがるのだけど、POSTしてみるとArrayで送れない。

仕方がないので、直接HTMLコードを書かないといけないらしい。

<select id="object_method" name="object[method][]" multiple="multiple">
<% for choice in choices %>
<option value="<%= choice %>"><%= choice %></option>
<% end %>
</select>

というのも、こちらに詳しく書かれています。

2006年02月17日

ActionView layout_for

views/layoutsにlayout用rhtmlファイルを用意し、<%= @content_for_layout %>で埋め込むことができるんだけど、javascriptなどを使っていて、どうしてもheaderに埋め込みたい場合は、<%= @content_for_ %>を使うとよい。
layoutのファイルには

<html>
<head>
<title>タイトル</title>
<%= @content_for_header %>
</head>
<body>
<%= @content_for_layout %>
</body>
</html>
ってしておいて、埋め込みたいviewに
<% content_for(:header) do %>
<%= javascript_include_tag "prototype" %>
<% end %>
ってしておくと、header内に埋め込まれる

About Ruby

ブログ「SANGA2000」のカテゴリ「Ruby」に投稿されたすべてのエントリーのアーカイブのページです。新しい順番に並んでいます。

前のカテゴリは@itです。

次のカテゴリはSanga2004です。

他にも多くのエントリーがあります。メインページアーカイブページも見てください。

Powered by
Movable Type