2008-09-08
レイルに乗ってみた〜Rails of Ruby on Rails その03「プラグインで躓いた(つдT)」
書籍『Rails of Ruby on Rails ~Case of LOCUSANDWONDERS.COM~』で勉強してみた(P76〜)
ユーザ認証機能をつける(gitでインスコ失敗)
プラグインのRestful-authenticationを使うので、とりあえずMacportsで『git』を入れる。
[注]git-coreいれなくてもよいかも? でもいずれ使うかもなので入れとく
sudo port install git-core
gitからrestful-authenticationをインストールする。
(『 Restful Authentication - yuum3のお仕事日記』さんを参考にしました)
~/work/locus $ script/plugin install git://github.com/technoweenie/restful-authentication.git removing: /Users/username/work/locus/vendor/plugins/restful-authentication/.git Initialized empty Git repository in /Users/username/work/locus/vendor/plugins/restful-authentication/.git/ remote: Counting objects: 415, done. remote: Compressing objects: 100% (282/282), done. remote: Total 415 (delta 142), reused 342 (delta 100) Receiving objects: 100% (415/415), 363.59 KiB | 220 KiB/s, done. Resolving deltas: 100% (142/142), done. Plugin not found: ["git://github.com/technoweenie/restful-authentication.git"]
あれ?Plugin not foundってインストール失敗?
別の方法でやってみる
『 認証機能:restful_authenticationを試してみる。 - 発声練習』さんを参考にrestful_authenticationをインストールしてみる
~/work/locus $ script/plugin install http://svn.techno-weenie.net/projects/plugins/restful_authentication/
+ ./README
+ ./Rakefile
+ ./generators/authenticated/USAGE
+ ./generators/authenticated/authenticated_generator.rb
+ ./generators/authenticated/templates/activation.html.erb
+ ./generators/authenticated/templates/authenticated_system.rb
+ ./generators/authenticated/templates/authenticated_test_helper.rb
+ ./generators/authenticated/templates/controller.rb
+ ./generators/authenticated/templates/fixtures.yml
+ ./generators/authenticated/templates/functional_spec.rb
+ ./generators/authenticated/templates/functional_test.rb
+ ./generators/authenticated/templates/helper.rb
+ ./generators/authenticated/templates/login.html.erb
+ ./generators/authenticated/templates/mailer.rb
+ ./generators/authenticated/templates/mailer_test.rb
+ ./generators/authenticated/templates/migration.rb
+ ./generators/authenticated/templates/model.rb
+ ./generators/authenticated/templates/model_controller.rb
+ ./generators/authenticated/templates/model_functional_spec.rb
+ ./generators/authenticated/templates/model_functional_test.rb
+ ./generators/authenticated/templates/model_helper.rb
+ ./generators/authenticated/templates/observer.rb
+ ./generators/authenticated/templates/signup.html.erb
+ ./generators/authenticated/templates/signup_notification.html.erb
+ ./generators/authenticated/templates/unit_spec.rb
+ ./generators/authenticated/templates/unit_test.rb
+ ./install.rb
+ ./lib/restful_authentication/rails_commands.rb
Restful Authentication Generator
====
This is a basic restful authentication generator for rails, taken
from acts as authenticated. Currently it requires Rails 1.2.6 or above.
To use:
./script/generate authenticated user sessions \
--include-activation \
--stateful
The first parameter specifies the model that gets created in signup
(typically a user or account model). A model with migration is
created, as well as a basic controller with the create method.
The second parameter specifies the sessions controller name. This is
the controller that handles the actual login/logout function on the
site.
The third parameter (--include-activation) generates the code for a
ActionMailer and its respective Activation Code through email.
The fourth (--stateful) builds in support for acts_as_state_machine
and generates activation code. This was taken from:
http://www.vaporbase.com/postings/stateful_authentication
You can pass --skip-migration to skip the user migration.
If you're using acts_as_state_machine, define your users resource like this:
map.resources :users, :member => { :suspend => :put,
:unsuspend => :put,
:purge => :delete }
Also, add an observer to config/environment.rb if you chose the
--include-activation option
config.active_record.observers = :user_observer # or whatever you
# named your model
Security Alert
====
I introduced a change to the model controller that's been tripping
folks up on Rails 2.0. The change was added as a suggestion to help
combat session fixation attacks. However, this resets the Form
Authentication token used by Request Forgery Protection. I've left
it out now, since Rails 1.2.6 and Rails 2.0 will both stop session
fixation attacks anyway.
今度は入ったみたい。
ユーザ認証用のモデルとコントローラを自動生成
~/work/locus $ script/generate authenticated user sessions
Ready to generate.
----------------------------------------------------------------------
Once finished, don't forget to:
- Add routes to these resources. In config/routes.rb, insert routes like:
map.signup '/signup', :controller => 'users', :action => 'new'
map.login '/login', :controller => 'sessions', :action => 'new'
map.logout '/logout', :controller => 'sessions', :action => 'destroy'
----------------------------------------------------------------------
We've create a new site key in config/initializers/site_keys.rb. If you have existing
user accounts their passwords will no longer work (see README). As always,
keep this file safe but don't post it in public.
----------------------------------------------------------------------
exists app/models/
exists app/controllers/
exists app/controllers/
exists app/helpers/
create app/views/sessions
exists app/controllers/
exists app/helpers/
create app/views/users
exists config/initializers
exists test/functional/
exists test/functional/
exists test/unit/
exists test/fixtures/
create app/models/user.rb
create app/controllers/sessions_controller.rb
create app/controllers/users_controller.rb
create lib/authenticated_system.rb
create lib/authenticated_test_helper.rb
create config/initializers/site_keys.rb
create test/functional/sessions_controller_test.rb
create test/functional/users_controller_test.rb
create test/unit/user_test.rb
create test/fixtures/users.yml
create app/helpers/sessions_helper.rb
create app/helpers/users_helper.rb
create app/views/sessions/new.html.erb
create app/views/users/new.html.erb
create app/views/users/_user_bar.html.erb
exists db/migrate
create db/migrate/20080908101516_create_users.rb
route map.resource :session
route map.resources :users
route map.signup '/signup', :controller => 'users', :action => 'new'
route map.register '/register', :controller => 'users', :action => 'create'
route map.login '/login', :controller => 'sessions', :action => 'new'
route map.logout '/logout', :controller => 'sessions', :action => 'destroy'
マイグレーション実行
~/work/locus $ rake db:migrate
AuthenticatedSystemの組み込み
app/controllers/sessions_controller.rb の以下の行コメントアウト
#include AuthenticatedSystem
そして、その行をapp/controllers/application.rb に追加
include AuthenticatedSystem
Beforeフィルタでユーザ認証
そしてその行をapp/controllers/entries_controller.rbに追加
before_filter :login_required, :except => [:index, :show]
ブラウザで動作確認
http://localhost:3000/entriesで記事の追加するとログイン画面
ユーザアカウント作成
http://localhost:3000/users/newでユーザ登録したらエラーに。
サーバを再起動(script/server )したら登録できた。
ユーザアカウントの作成を制限する
app/controllers/users_controller.rb次をコメントアウト、と一行追加。
#include AuthenticatedSystem before_filter :login_required
ルーティングを修正
config/routes.rbに追加
map.signup '/signup', :controller => 'users', :action => 'new' map.login '/login', :controller => 'sessions', :action => 'new' map.logout '/logout', :controller => 'sessions', :action => 'destroy'
これで例えばhttp://localhost:3000/logoutに行けばログアウトできるようになる。
管理用のボタン類をログイン時のみ表示する
app/views/entries/index.html.erbの「link_to('記事の追加',〜」の行にif logged_in?を追加
<%= link_to('記事の追加', new_entry_path, :class => "operation") if logged_in? %>
app/views/entries/_entry.html.erbの「<dd>link_to '編集'〜</dd>」あたりを修正
<dd> <% content_tag :dd, :class => "operation" do %> <%= link_to '編集', edit_entry_path(entry) %> <%= link_to '削除', entry, :confirm => '本当によろしいですか?', :method => :delete %> <% end if logged_in? %> </dd>
確実にサーバ再起動してみた
ブラウザの表示がおかしいので、サーバの再起動を確実にやってみた。 (バックアップ取りつつやってるからかも)
control + c でサーバ止める。
cd cd work/locus script/server
メモ
今日はここまで。
レイルに乗ってみた〜Rails of Ruby on Rails その02「GetTextで躓いた(つдT)」
書籍『Rails of Ruby on Rails ~Case of LOCUSANDWONDERS.COM~』で勉強してみた(p062〜)
レイアウトを変更する
app/views/layouts/entries.html.erbに変更・追加
<title>Blog</title>
:
<div id="container">
<ul id="navi">
<li id="naviBlog"><%= link_to 'Blog',
entries_path %></li>
</ul>
<h1><%= image_tag 'blog_header.jpg' %></h1>
<%= content_tag(:div, flash[:notice],
:id => 'notice') if flash[:notice] %>
<div id="content">
:
</div>
</div>
public/ディレクトリにあるimagesとstylesheetsをRails of Ruby on Rails サポートサイトからダウンロードしたサンプルのものと入れ替える。
次は若干端折ってパーシャル使ってみる(_entry.html.erb、_form.html.erb)
パーシャルを利用してDRYに実装
app/views/entries/_entry.html.erbファイル作成して書籍P68のとおり書くと、なぜかブラウザで「編集」「削除」あたりの表示がおかしくなる(『"operation"> 編集 削除』と表示される)
<dd class => "operation"%> <%= link_to '編集', edit_entry_path(entry) %> <%= link_to '削除', entry, :confirm => '本当によろしいですか?', :method => :delete %>
の部分を
<dd> <%= link_to '編集', edit_entry_path(entry), :class => "operation"%> <%= link_to '削除', entry, :confirm => '本当によろしいですか?', :method => :delete, :class => "operation"%>
にしたら書籍と同じ表示になった。
同じディレクトリにある「index.html.erb」と「show.html.erb」も書籍にそって書き直す。
それから同じように「_form.html.erb」はファイルを作って、「new.html.erb」「edit.html.erb」それぞれ書き直す。
バリデーションを使ってフォームの入力内容を検証する
「app/models/entry.rb」
class Entry < ActiveRecord::Base validates_presence_of :title, :content end
と一行追加して、ブラウザで確認。新規作成時にタイトルと記事に何もいれないとエラーでる。英語で。
Ruby-GetText-Packageをインストール
[訂正]Macportsでrb-gettextをインストール追加
日本語対応にするためでRuby-GetText-Packageを、Macportsもしくはgemでインストール。
ターミナルから
Macportsでインストールの場合
sudo port install rb-gettext
gemでインストールの場合
sudo gem install gettext
[重要!!]
ここから書籍のままやるとエラーになるので『Rails2.0から2.1への移行を試してみる - ザリガニが見ていた...。』さんを参考にごにょごにょしてみた。
- 「config/environment.rb」に「require 'gettext/rails'」は書かない!
- /config/initializers/gettext.rbを新規に作って以下内容を書く。
require 'gettext/rails' module ActionView class Base delegate :file_exists?, :to => :finder unless respond_to?(:file_exists?) end end
以上、書籍外情報でした。
書籍に戻って
「app/controllers/application.rb」(helper :all〜の下あたり)に
init_gettext "locus"
を追加。サーバを再起動して確認(script/server )
(〜p075)
とりあえず
レイルに乗ってみた〜Rails of Ruby on Rails その01「はじめてみる」
[訂正] はてな記法を間違い、単独で表示されなくなってたのを修正。正『||<』、誤『|<<』
はじまり
勝手に師事することにしたyugui師匠が絶賛していたので、この書籍でRuby on Railsの勉強することにした。(内容はとても素晴らしい(・∀・))
Rails2.1とCabon Emacsで
書籍はRails2.0対応で開発環境はNetBeansですが、Rails2.1とCabon Emacsでやってみる(MacOSX10.4)。
- その問題点・補足など
- 見事につまずきまくり(´・ω・`)。
- Rails2.0->2.1の非互換性が思いのほか大きくて吃驚(||゚Д゚)。
- 上記理由?により書籍と順序が若干入れ替わっていたり(データベース作成あたり)
- Rails of Ruby on Rails サポートサイトのサンプル動かなかったし(つдT)
- Webアプリとか何なのか知識足りていない自分...(´・ω・`)
- Rubyをほとんど理解してない自分...(||゚Д゚)
- 不安材料山積みですが...
やり遂げます...たぶん
開発環境構築
『Ruby』と『Ruby on Rails』『Carbon Emacs』をインストール
(過去のエントリーとか参照 MacPortsでRubyとかRailsなどインストールしてみた - 牌語備忘録とか)
Chapter 02 プロジェクト作成
~ $ cd work
~/work $ rails locus
create
create app/controllers
create app/helpers
create app/models
create app/views/layouts
create config/environments
create config/initializers
create db
create doc
create lib
create lib/tasks
create log
create public/images
create public/javascripts
create public/stylesheets
create script/performance
create script/process
create test/fixtures
create test/functional
create test/integration
create test/unit
create vendor
create vendor/plugins
create tmp/sessions
create tmp/sockets
create tmp/cache
create tmp/pids
create Rakefile
create README
create app/controllers/application.rb
create app/helpers/application_helper.rb
create test/test_helper.rb
create config/database.yml
create config/routes.rb
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/initializers/new_rails_defaults.rb
create config/boot.rb
create config/environment.rb
create config/environments/production.rb
create config/environments/development.rb
create config/environments/test.rb
create script/about
create script/console
create script/dbconsole
create script/destroy
create script/generate
create script/performance/benchmarker
create script/performance/profiler
create script/performance/request
create script/process/reaper
create script/process/spawner
create script/process/inspector
create script/runner
create script/server
create script/plugin
create public/dispatch.rb
create public/dispatch.cgi
create public/dispatch.fcgi
create public/404.html
create public/422.html
create public/500.html
create public/index.html
create public/favicon.ico
create public/robots.txt
create public/images/rails.png
create public/javascripts/prototype.js
create public/javascripts/effects.js
create public/javascripts/dragdrop.js
create public/javascripts/controls.js
create public/javascripts/application.js
create doc/README_FOR_APP
create log/server.log
create log/production.log
create log/development.log
create log/test.log
~/work $
開発用webサーバ起動
ターミナルとか別にウインドウ開いて
cd work /locus/ script/server
ブラウザでhttp://localhost:3000/を確認
スキャッフォールドジェネレータを実行
~/work $ cd locus/
~/work/locus $ ls
README app db lib public test vendor
Rakefile config doc log script tmp
~/work/locus $ script/generate scaffold entry title:string content:text
exists app/models/
exists app/controllers/
exists app/helpers/
create app/views/entries
exists app/views/layouts/
exists test/functional/
exists test/unit/
exists public/stylesheets/
create app/views/entries/index.html.erb
create app/views/entries/show.html.erb
create app/views/entries/new.html.erb
create app/views/entries/edit.html.erb
create app/views/layouts/entries.html.erb
create public/stylesheets/scaffold.css
create app/controllers/entries_controller.rb
create test/functional/entries_controller_test.rb
create app/helpers/entries_helper.rb
route map.resources :entries
dependency model
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/entry.rb
create test/unit/entry_test.rb
create test/fixtures/entries.yml
create db/migrate
create db/migrate/20080908010337_create_entries.rb
~/work/locus $
Chapter 03 ブログの作成 マイグレーションを実行しデータベース作成
~/work/locus $ rake db:migrate (in /Users/username/work/locus) == 20080908010337 CreateEntries: migrating ==================================== -- create_table(:entries) -> 0.0129s == 20080908010337 CreateEntries: migrated (0.0133s) ===========================
ブラウザでhttp://localhost:3000/entriesを確認(注意!entryが複数形のentriesになる)
New entryで2つ3つ作ったり削除したりしてみる