ミームの死骸を待ちながら

We are built as gene machines and cultured as meme machines, but we have the power to turn against our creators. We, alone on earth, can rebel against the tyranny of the selfish replicators. - Richard Dawkins "Selfish Gene"

We are built as gene machines and cultured as meme machines, but we have the power to turn against our creators.
We, alone on earth, can rebel against the tyranny of the selfish replicators.
- Richard Dawkins "Selfish Gene"

画面表示とRuby パスワード認証hash化

MVCモデルのイメージをしっかりアタマに入れる◆
ショッピングサイトの例(多分DHH本RailsによるアジャイルWebアプリケーション開発)で、カートの内容も購入ページに入れる。checkoutのビューに次の記述をする。

<%= render_component( :action => 'cart' ) %>

これではレイアウト全体が入れ子に。×。そこで、 :checkoutという目印をつける。

<%= render_component( :action => 'cart', :params => { :context => :checkout } ) %>

そして、cartメソッドの最後に ifで場合わけ。

if params[:context] == :checkout
render( :layout => false )
end

これで、レイアウトの表示が抑止され見栄えがよくなる。
で、「購入する」とかはずすには、

<% if __FILE__ == $0 %>

<%= link_to 'カートを空にする', :action => 'clear_cart' %>

<%= link_to '購入する', :action => 'checkout' %>

<% else %>
(空白)<% end %>

てな感じで、<% %>で囲ってRubyってやったが、だめらしいorz...ブラウザ介すのでこの方法では別ファイルからの参照とみなされ、通常時も表示されない。
hashのをこっちにも応用して解決。送ったhashが==か否かで場合分け。

if params[:context] == :checkout

パスワードも確認とふたつ取って一緒かどうか認証。ハッシュ化するメソッドがある。

if password.empty?
@user.hashed_password = '' #これでpresenceのvalidationにひっかかる
else
@user.hashed_password = Digest::SHA1.hexdigest(password)
end
if @user.save #hashにして保存
flash[:notice] = 'ユーザを追加しました'
redirect_to( :action => 'list_users' )
else
render :actioin => 'add_user'
end


で、ユーザ管理。admin下につくるので以下にのように。

$ script/generate controller Admin::User index add_user delete_user list_users

引数にとったやつらが、controllerのクラス内でメソッドとして出てる。

layoutは流用したなら、中身だけ書けばいい。その中身が、layout/sth.rhtmlに出てくるyieldで呼び出されている。

クラスに属さないのとってくるなら_tag最後につける。password_field_tag。
Railsにおいてアクションとは、コントローラの同名のインスタンスメソッドを実行→同名のrhtmlファイルを作って飛ぶ。
で、render :actionはこれ。renderは他のオプション取ることで色々な挙動。