12/04/2007

activescaffold + acts_as_authenticated レシピ

activescaffold + acts_as_authenticated レシピ


$ rails qplan
$ cd qplan
$ ./script/plugin install http://activescaffold.googlecode.com/svn/tags/active_scaffold
$ ./script/plugin install acts_as_authenticated

そのほか日本語対応のための設定やデータベースの設定が必要。sqlite3を使うにはdatabase.ymlで

adapter: sqlite3
database: db/development.sqlite3


○acts_as_authenticatedのための準備


$ ./script/generate authenticated user(モデル名) #{account}(コントローラ名)

認証用のテーブル(モデル)を作るためのマイグレーションファイルがdb/migrateに作られる。

$ rake db:migrate

./app/controller/#{account}_controller.rbにある以下のメソッド達をapplication.rbにコピー



include AutheticationSystem # 必ず入れよ

def index
redirect_to(:action => 'signup') unless logged_in? || User.count > 0
end

def login
return unless request.post?
self.current_user = User.authenticate(params[:login], params[:password])
if logged_in?
if params[:remember_me] == "1"
self.current_user.remember_me
cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
end
redirect_back_or_default(:controller => '/mroadmap', :action => 'index')
flash[:notice] = "Logged in successfully"
end
end

def signup
@user = User.new(params[:user])
return unless request.post?
@user.save!
self.current_user = @user
redirect_back_or_default(:controller => '/mroadmap', :action => 'index')
flash[:notice] = "Thanks for signing up!"
rescue ActiveRecord::RecordInvalid
render :action => 'signup'
end

def logout
self.current_user.forget_me if logged_in?
cookies.delete :auth_token
reset_session
flash[:notice] = "You have been logged out."
redirect_back_or_default(:controller => '/mroadmap', :action => 'index')
end



認証が必要なコントローラには、./app/controllers/#{controller}_controller.rbに次の1行を挿入。

class #{なんちゃら}Controller < ApplicationController
before_filter :login_required

○activescaffoldのための準備

$ ./script/generate migrate CreateTables
./db/migration/0XX_create_tables.ymlを編集 (Mytableというモデルを作ったとする)
$ rake db:migrate
$ ./script/generate model --skip-migrate Mytable
$ ./script/generate controller mytable
./app/controller
./app/views/layouts/mylayouts.rhtmlを以下のように編集して保存。




<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>My Application</title>
<%= javascript_include_tag :defaults %>
<%= active_scaffold_includes %>
</head>
<body>
<%= yield %>
</body>
</html>


./app/controller/#{controller}_controller.rbに次の宣言

class #{なんちゃら}Controller < ApplicationController
before_filter :login_required # 認証の利用宣言

active_scaffold :mytable do |config|
# ここに設定をいれる
end
layout "mylayout" #./app/views/layouts/mylayout.rhtmlのこと
end


○HABTMを使うとき。

たとえば2つのテーブルtableaとtablebがあったら./db/migrate/0xx_*ファイルを次のようにしてみる。



def self.up
create_table "tablea" do |t|
t.column "noa", :integer
t.column "plana", :text
t.column "created_at", :date
t.column "updated_at", :date
end

create_table "tableb" do |t|
t.column "nob", :integer
t.column "year", :integer
t.column "planb", :text
t.column "created_at", :date
t.column "updated_at", :date
end

create_table "tableas_tablebs", :id => false do |t|
t.column "tablea_id", :integer, :default => 0, :null => false
t.column "tableb_id", :integer, :default => 0, :null => false
end

end



さらにモデルtablea,tablebで次のような宣言をしておく。対称なのでaとbを入れ替えよ。



has_and_belongs_to_many :tableas
def to_label
"#{noa}"
end



noaはcolumnの名前だ。

○GetTextを『使わない』日本語化
次のファイルを./lib/japanize.rbとして保存し、./config/environment.rbの最後に次の1行を追加。

require "japanize"


./lib/japanize.rb



class Object
AS_JP_MAP = {
"Replace With New" => "新しい値に置換",
"Edit" => "編集",
"Show" => "表示",
"Update" => "更新",
"Delete" => "削除",
"Search" => "検索",
"Create New" => "新規作成",
"Reset" => "リセット",
"hide" => "隠蔽",
"show" => "表示",
"Cancel" => "キャンセル",
"Found" => "件見つかりました。",
"Create" => "作成",
"Close" => "閉じる",
"No Entries" => "データがありません",
"Live Search" => "リアルタイム検索",
"Search Terms" => "検索ワード",
"Create %s" => "%sの新規作成",
'Create Another' => "新規追加",
'Add From Existing'=> "を追加",
'- select -' => "-- 選択 --",
'Remove' => "除外",
'Previous' => "前",
'Next' => "次",
'%s for %s' => "%2$s の %1$s (%1$s for %2$s)",
'Update %s' => "%sの編集",
'Are you sure?' => "本当によろしいですか?",
'Request Failed (code 500, Internal Error)' => "エラーが発生しました。",
'Created %s' => "%s を作成しました。",
'Deleted %s' => "%s を削除しました。",
'Updated %s' => "%s を更新しました。",
"Version inconsistency - this record has been modified since you started editing it." => "更新が衝突しました。",
'Show %s' => "%s の表示",
"no options" => "選択肢がありません。"
}
alias_method :as__without_jp, :as_
def as__with_jp(*args)
pars = args.dup
fmt = pars.shift
text = AS_JP_MAP[fmt]
if text
text = text % pars unless pars.empty?
return text
end
return as__without_jp(*args)
end
alias_method :as_, :as__with_jp
end