rails3+DataMapperでdeviseを使う

deviseの導入

deviseはRackベースの認証システムです。
今回は、DataMapper用のdeviseを使用します。

$ vi Gemfile
 ---------------
 gem 'dm-devise'      <- 追加
 ---------------

devise用ライブラリのインストール

 $ bundle install
 $ rails g devise:install

deviseのセットアップ

public/index.htmlファイルの削除

 $ rm public/index.html

routes.rbの編集

  $ vi config/routes.rb
 ---------------
 root :to => "welcome#index" 
 ---------------

welcomeコントローラーは後で作ります。

application.html.erbの編集

  $ vi app/view/layout/application.html.erb
 ---------------
 <%= link_to('Sign out', [:destroy, current_user, :session],:class => 'signOut') if current_user%>

 <%= content_tag(:p, notice, :class => 'notice') %>  <- 追加
 <%= content_tag(:p, alert, :class => 'alert') %>    <- 追加
 <%= yield %>
 ---------------

welcomeコントローラーの作成

 $ rails g controller welcome index

サーバーを起動

 $ rails s

ブラウザでこのように表示されるとOKです。

deviseが使用する標準のビューを作成

 $ rails g devise:views

userモデルの作成

 $ rails g devise user

マイグレーションの実行

 $ rake db:automigrate

routes.rbの編集

  $ vi config/routes.rb
 ---------------
 root :to => "welcome#index" 
 devise_for :users

 get 'hoges', :to => 'hoges#index', :as => :user_root
 resources :hoges
 ---------------

devise_for :users でユーザー登録、ログインフォームへの経路が設定されます。
get 'hoges', :to => 'hoges#index', :as => :user_rootは、ユーザー認証後のリダイレクト先を指定。

welcome#indexの編集

以下を追記。

 $ vi app/view/welcome/index.html.erb
 ---------------
<%= content_tag(:p) do %>
  <%= link_to "ログイン", [:new, :user_session] %>
<% end -%>

<%= content_tag(:p) do %>
  <%= link_to "ユーザー登録", [:new, :user_registration] %>
<% end -%>

<%= content_tag(:p) do %>
  <%= link_to "パスワード再発行", [:new, :user_password] %>
<% end -%>
 ---------------

welcomeコントローラーの修正

 class WelcomeController < ApplicationController
   def index
     if current_user
       redirect_to :user_root
       return
     end
   end
 end

hogesコントローラーの修正

 class HogesController < ApplicationController
   before_filter :authenticate_user!  <- 追加

   (省略)
 end

サーバーを起動

 $ rails s

ブラウザでこのように表示されるとOKです。

ユーザー登録後、hoges#indexに移動すれば完了です。