<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
		xmlns:xhtml="http://www.w3.org/1999/xhtml"
>

<channel>
	<title>imishin.com &#187; tutorial</title>
	<atom:link href="http://blog.imishin.com/tag/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.imishin.com</link>
	<description></description>
	<lastBuildDate>Thu, 05 May 2011 16:30:31 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<xhtml:link rel="alternate" media="handheld" type="text/html" href="http://blog.imishin.com/tag/tutorial/feed/" />
		<item>
		<title>restful-authentication プラグインを使ってログインアプリケーション作る（2）</title>
		<link>http://blog.imishin.com/2008/10/07/rails-with-restful-authentication-2/</link>
		<comments>http://blog.imishin.com/2008/10/07/rails-with-restful-authentication-2/#comments</comments>
		<pubDate>Tue, 07 Oct 2008 02:10:37 +0000</pubDate>
		<dc:creator>kusakari</dc:creator>
				<category><![CDATA[RubyOnRails]]></category>
		<category><![CDATA[restful-authentication]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.imishin.com/?p=238</guid>
		<description><![CDATA[前回作った todo アプリケーションにメールアドレス変更機能と、エラーメッセージ・メールの日本語化を追加します。 メールアドレス変更機能 change_email プラグインをインストールします。 ruby scrip [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.imishin.com/wp-content/uploads/2008/10/todos_ja.png"><img class="alignnone size-medium wp-image-242" title="todos_ja" src="http://blog.imishin.com/wp-content/uploads/2008/10/todos_ja-300x240.png" alt="" width="300" height="240" /></a></p>
<p><a href="http://blog.imishin.com/2008/09/14/rails-with-restful-authentication-on/">前回</a>作った todo アプリケーションにメールアドレス変更機能と、エラーメッセージ・メールの日本語化を追加します。</p>
<p><span id="more-238"></span></p>
<h3>メールアドレス変更機能</h3>
<p>change_email プラグインをインストールします。</p>
<pre class="prettyprint">ruby script/plugin install git://github.com/kusakari/change_email.git</pre>
<p>依存しているプラグインをインストールします。（valid-attributes）</p>
<pre class="prettyprint">ruby script/plugin install git://github.com/kusakari/valid_attributes.git</pre>
<p>メールアドレス保存用のコードを自動生成します。</p>
<pre class="prettyprint">ruby script/generate change_email email user</pre>
<p>migrate します。</p>
<pre class="prettyprint">rake db:migrate</pre>
<p>これで、以下の URL からメールアドレスを変更することができます。（ログイン後のみ）</p>
<blockquote><p>http://localhost:3000/change_email</p></blockquote>
<h3>エラーメッセージの日本語化</h3>
<p>RailsJa プラグインをインストールします。</p>
<pre class="prettyprint">ruby script/plugin install git://github.com/kusakari/rails-ja.git</pre>
<p>次に、app/models/todo.rb を変更します。</p>
<p>以下のようにして、@@humanized_attribute_names にアトリビュートごとの名称を設定します。</p>
<p>human_model_name は日本語モデル名を返すようにします。</p>
<pre class="prettyprint">class Todo &lt; ActiveRecord::Base
  validates_presence_of     :name
  validates_length_of       :name,    :within =&gt; 1..100
  class &lt;&lt; self
    @@humanized_attribute_names = {
      "name" =&gt; "タスク名",
    }
    def human_model_name
      "Todo"
    end
  end
end</pre>
<h3>メールの日本語対応</h3>
<p>ActionMailerJa プラグインはインストールするだけで日本語対応できる ActionMailer 拡張です。</p>
<pre class="prettyprint">ruby script/plugin install git://github.com/kusakari/actionmailer-ja.git</pre>
<p>ActionMailerJa はメールヘッダの Subject, From, Cc, Recipients の日本語化にも対応しているため、</p>
<p>例えば、app/models/user_mailer.rb の場合、以下のように変更します。</p>
<pre class="prettyprint">class UserMailer &lt; ActionMailer::Base
  def signup_notification(user)
    setup_email(user)
    @subject    += '新しいアカウントを有効にして下さい'

    @body[:url]  = "#{$SERVICE_URL}/activate/#{user.activation_code}"

  end

  def activation(user)
    setup_email(user)
    @subject    += 'アカウントが有効になりました'
    @body[:url]  = "#{$SERVICE_URL}"
  end

  protected
    def setup_email(user)
      @recipients  = "#{user.email}"
      @from        = "TODOアプリケーション &lt;#{$ADMIN_EMAIL}&gt;"
      @subject     = "[YOURSITE] "
      @sent_on     = Time.now
      @body[:user] = user
    end
end</pre>
<p>以上でメールアドレスの変更機能と、エラーメッセージ・メールの日本語対応ができました。</p>
<p>僕が現時点で Ruby on Rails を選択するのは、他のフレームワークでは、</p>
<p>ここまでの機能を同じくらい高速で汎用的に開発することはできないと思っているからです。</p>
<p>これはもちろん Ruby という言語によるものが大きいと思います。</p>
<p>ということで Ruby on Rails のメリットを最大限活かせるように、プラグインやジェネレータを積極的に作っていきたいと思います。</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.imishin.com/2008/10/07/rails-with-restful-authentication-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<xhtml:link rel="alternate" media="handheld" type="text/html" href="http://blog.imishin.com/2008/10/07/rails-with-restful-authentication-2/" />
	</item>
		<item>
		<title>restful-authentication プラグインを使ってログインアプリケーション作る（1）</title>
		<link>http://blog.imishin.com/2008/09/14/rails-with-restful-authentication-on/</link>
		<comments>http://blog.imishin.com/2008/09/14/rails-with-restful-authentication-on/#comments</comments>
		<pubDate>Sun, 14 Sep 2008 14:39:47 +0000</pubDate>
		<dc:creator>kusakari</dc:creator>
				<category><![CDATA[RubyOnRails]]></category>
		<category><![CDATA[restful-authentication]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.imishin.com/?p=140</guid>
		<description><![CDATA[数回に分けてログインアプリケーションを一通り作るためのまとめを書いてみます。 Project の作成 今回は何でもいいので、とりあえず todo を作成してみます。 rails todo Plugin Install 必 [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.imishin.com/wp-content/uploads/2008/10/todos.jpg"><img class="alignnone size-medium wp-image-236" title="todos" src="http://blog.imishin.com/wp-content/uploads/2008/10/todos-300x131.jpg" alt="" width="300" height="131" /></a></p>
<p>数回に分けてログインアプリケーションを一通り作るためのまとめを書いてみます。</p>
<p><span id="more-140"></span></p>
<h2>Project の作成</h2>
<p>今回は何でもいいので、とりあえず todo を作成してみます。</p>
<pre class="prettyprint">rails todo</pre>
<h2>Plugin Install</h2>
<p>必要なプラグインをあらかじめインストールしておきます。</p>
<h3>restful-authentication</h3>
<pre class="prettyprint">ruby script/plugin install git<span class="synIdentifier">:/</span>/github.com/technoweenie/restful-authentication.git</pre>
<h3>aasm</h3>
<pre class="prettyprint">gem sources -a http://gems.github.com
gem install rubyist-aasm</pre>
<h3>forgot_password</h3>
<pre class="prettyprint">ruby script/plugin install git://github.com/greenisus/forgot_password.git</pre>
<h2>Generate</h2>
<p>sessions_controller と user モデルを作成します。</p>
<pre class="prettyprint">ruby script/generate authenticated user sessions --include-activation --aasm</pre>
<p>passwords_controller と password モデルを作成します。</p>
<pre class="prettyprint">ruby script/generate forgot_password password user</pre>
<h2>その他修正箇所</h2>
<p>このままでは動作しないので、aasm 関係を読み込むように修正します。</p>
<p>vendor/plugins/restful-authentication/init.rb</p>
<pre class="prettyprint">require File.dirname(__FILE__) + '/lib/authentication'
require File.dirname(__FILE__) + '/lib/authentication/by_password'
require File.dirname(__FILE__) + '/lib/authentication/by_cookie_token'
+require 'aasm'
+require File.dirname(__FILE__) + '/lib/authorization/aasm_roles'</pre>
<p>アクティベーション用の route を追加。<br />
config/routes.rb</p>
<pre class="prettyprint">（省略）
  map.activate '/activate/:activation_code', :controller =&gt; 'users', :action =&gt; 'activate'
（省略）</pre>
<p>メールの設定をします。</p>
<p>config/environment.rb</p>
<pre class="prettyprint">（省略）
Rails::Initializer.run do |config|
（省略）
  config.active_record.observers = :user_observer

  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :address =&gt; 'SMTP サーバ',
    :port =&gt; 587, # or 25
    :domain =&gt; 'ドメイン',
    :authentication =&gt; :login,
    :user_name =&gt; 'SMTP AUTH ユーザーID',
    :password =&gt; 'SMTP AUTH パスワード'
  }
end

$ADMIN_EMAIL = '管理者のメールアドレス'
$SERVICE_URL = 'http://localhost:3000'</pre>
<p>メールアドレスと URL を設定します。</p>
<p>app/models/user_mailer.rb</p>
<pre class="prettyprint">class UserMailer &lt; ActionMailer::Base
  def signup_notification(user)
    setup_email(user)
    @subject    += 'Please activate your new account'

    @body[:url]  = "#{$SERVICE_URL}/activate/#{user.activation_code}"

  end

  def activation(user)
    setup_email(user)
    @subject    += 'Your account has been activated!'
    @body[:url]  = "#{$SERVICE_URL}"
  end

  protected
    def setup_email(user)
      @recipients  = "#{user.email}"
      @from        = $ADMIN_EMAIL
      @subject     = "[YOURSITE] "
      @sent_on     = Time.now
      @body[:user] = user
    end
end</pre>
<p>app/models/password_mailer.rb</p>
<pre class="prettyprint">class PasswordMailer &lt; ActionMailer::Base

  def forgot_password(password)
    setup_email(password.user)
    @subject    += 'You have requested to change your password'
    @body[:url]  = "#{$SERVICE_URL}/change_password/#{password.reset_code}"
  end

  def reset_password(user)
    setup_email(user)
    @subject    += 'Your password has been reset.'
  end

  protected
    def setup_email(user)
      @recipients  = "#{user.email}"
      @from        = $ADMIN_EMAIL
      @subject     = "[YOURSITE] "
      @sent_on     = Time.now
      @body[:user] = user
    end
end</pre>
<p>今回はすべてのコントローラのアクションを認証対象とするため、</p>
<p>application.rb で AuthenticatedSystem を読み込み、login_required を設定します。</p>
<p>app/controllers/application.rb</p>
<pre class="prettyprint">class ApplicationController &lt; ActionController::Base

（省略）
  include AuthenticatedSystem

  before_filter :login_required

end</pre>
<p>認証が必要ないアクションは except に指定します。</p>
<p>app/controllers/users_controller.rb</p>
<pre class="prettyprint">class UsersController &lt; ApplicationController
  before_filter :login_required, :except =&gt; [ :new,
                                              :create,
                                              :activate,
                                              :suspend,
                                              :unsuspend,
                                              :destroy,
                                              :purge,
                                            ]

（省略）

end</pre>
<p>sessions_controller は認証が必要ないため、skip_before_filter を設定します。</p>
<p>app/controllers/sessions_controller.rb</p>
<pre class="prettyprint">class SessionsController &lt; ApplicationController
  skip_before_filter :login_required

（省略）

end</pre>
<h2>起動準備</h2>
<p>config/database.yml を設定して下さい。</p>
<p>todo scaffold を作成。</p>
<pre class="prettyprint">ruby script/generate scaffold todo name:string</pre>
<p>app/views/layouts/todo.html.erb を application.html.erb に変更します。</p>
<p>データベースとテーブルの作成。</p>
<pre class="prettyprint">rake db:create

rake db:migrate</pre>
<p>ここまで設定することで、httpd を起動すると以下の動作確認することができます。</p>
<ul>
<li>ユーザー登録</li>
<li>ログイン</li>
<li>ログアウト</li>
<li>パスワードリセット</li>
<li>アクティベーション（メール、パスワードリセット）</li>
</ul>
<p>httpd は以下のコマンドで起動できます。</p>
<pre class="prettyprint">ruby script/server</pre>
<p>動作確認のための URL は以下の通り。</p>
<blockquote><p># 会員登録<br />
htt://localhost:3000/signup<br />
# ログイン<br />
htt://localhost:3000/login<br />
# ログアウト<br />
htt://localhost:3000/logout<br />
# todo 一覧<br />
htt://localhost:3000/todos</p></blockquote>
<p>次回はこの todo にメールアドレス変更機能を追加し、日本語化してみます。</p>
<h2>参考</h2>
<p><a href="http://d.hatena.ne.jp/zariganitosh/20080903/1220412035" target="_blank">aasmとは何か？acts_as_state_machineとの違いは？</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.imishin.com/2008/09/14/rails-with-restful-authentication-on/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	<xhtml:link rel="alternate" media="handheld" type="text/html" href="http://blog.imishin.com/2008/09/14/rails-with-restful-authentication-on/" />
	</item>
	</channel>
</rss>

