ubuntu, ror, jQuery, css, website memo
太嫩, 沒啥心得, 用來紀錄每天學的
2009年9月10日 星期四
Railscast skill (6)
Restricting Access
helper_method 可以把某些controller 的method 弄到helper 一起用
<br /><!-- episodes/index.rhtml --><br /><% if admin? %><br /> <%= link_to 'New Episode', new_episode_path %><br /><% end %><br /><br /># controllers/application.rb<br />helper_method :admin?<br /><br />protected<br /><br />def admin?<br /> false<br />end<br /><br />def authorize<br /> unless admin?<br /> flash[:error] = "unauthorized access"<br /> redirect_to home_path<br /> false<br /> end<br />end<br /><br /># episodes_controller.rb<br />before_filter :authorize, :except => :index<br />
Console Tricks
<br /># 好一個 sandbox<br />ruby script/console --sandbox<br />Loading development environment in sandbox (Rails 2.2.2)<br />Any modifications you make will be rolled back on exit<br />>><br /><br /># 好一個 y<br />>> y User.first<br />--- !ruby/object:User <br />attributes: <br /> updated_at: 2009-09-10 06:45:46<br /> email_notify: "1"<br /> remember: "0"<br /> nickname: shlee<br /> id: "1"<br /><br /># helper<br />>> helper.text_field_tag :foo<br />=> "<input id=\"foo\" name=\"foo\" type=\"text\" />"<br /><br /># app 好物, hash_for_............ 好物<br />>> app.methods.grep(/_path$/)<br />>> app.homepage_path<br />=> "/"<br />>> app.hash_for_homepage_path<br />=> {:action=>"index", :only_path=>true, :controller=>"tc2", :use_route=>:homepage}<br /><br /># 可以自訂method 在 ~/.irbrc 裡<br />
Handling Exceptions
<br />#除了在 在product.rb 裡的設定<br />config.action_controller.consider_all_requests_local = false<br /><br />#還必須在application controller裡overwrite 掉 local_request? 這樣你在那邊用localhost:3000 它才會認出你是localhost 來的, 這樣才會丟500那種頁面給你<br /># 所以其實也可以在裡面多加上 admin 的判斷 如果是admin 的話 就讓它丟那種詳細的 error message<br /># application.rb<br />def local_request?<br /> false<br />end<br /><br />#要overwirte 一些exception 就可以在這用<br />def rescue_action_in_public(exception)<br /> case exception<br /> when ActiveRecord::RecordNotFound<br /> render :file => "#{RAILS_ROOT}/public/404.html", :status => 404<br /> else<br /> super<br /> end<br />end<br />
Catch-all Route
可以利用這招把所有奇怪的route 路徑都拿去 在controller 裡面在做些有的沒的處理
<br /># routes.rb<br />map.connect '*path', :controller => 'redirect', :action => 'index'<br /><br /># redirect_controller.rb<br />def index<br /> product = Product.find(:first, :conditions => ["name LIKE ?", "#{params[:path].first}%"])<br /> redirect_to product_path(product)<br />end<br />
沒有留言:
張貼留言
較新的文章
較舊的文章
首頁
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言