ITeye博客

beast学习笔记——3,application_controller

helloqidi · 2010-12-22 16:36 · ROR · 编程语言 · Markdown

beast学习笔记——3,application_controller

参考

http://www.iteye.com/topic/78885、

http://blog.csdn.net/jlaky/archive/2008/11/26/3378635.aspx(及其重要的学习资源)

http://2015.iteye.com/blog/604377(关于CSRF跨站请求伪造与protect_from_forgery**)**

http://blog.ashchan.com/archive/2008/11/24/rails-i18n-activerecord-model-human-name-made-easy/(I18N简介)

http://hlee.iteye.com/blog/422693(I18N英文介绍)

 

1,

(1)代码:

  include AuthenticatedSystem

  before_filter :set_language
  before_filter :login_required, :only => [:new, :edit, :create, :update, :destroy]

(2)表示:

调用插件AuthenticatedSystem,使用前置过滤器,其中login_required只对new, edit, create, update, destroy方法有效

 

2,

(1)代码

  helper :all
  helper_method :current_page

(2)表示

【1】helper :all,表示application_controller控制器将include所有的app/helpers目录下的helper。又因为application_controller是根控制器,所以,所有的视图view都可以用所有app/helpers目录下的helper

【2】helper_method方法,可以把controller中的方法定义为helper方法并可以在视图view中应用。又因为application_controller是根控制器,所以,所有的视图view都可以用current_page方法。

 

3,

(1)代码:

  # Uncomment the :secret if you're not using the cookie session store
  protect_from_forgery # :secret => 'e125a4be589f9d81263920581f6e4182'

(2)表示
如果没有使用rails2默认的cookie存储session的方式,就需要取消secret的注释,以保证不受CSRF****跨站请求伪造。

  protect_from_forgery与environment.rb中的config.action_controller.session配合使用

 

4,

(1)代码

  # Filter password parameter from logs
  filter_parameter_logging :password

(2)表示

过滤那些不希望被日志文件记录的信息,比如password,从而避免通过日志来泄露敏感信息。

 

5,

(1)代码

  def set_language
    I18n.locale = :en || I18n.default_locale
  end

(2)表示使用en作为locale,或者使用默认的I18n设置作为locale

I18n是rails2.2以后引入的模块,用于实现框架的国际化。

比方说有这样一个 User model:

 

# == Schema Information

# Schema version: 20081028111521

#

# Table name: users

#

#  id                   :integer         not null, primary key

#  login                :string(255)     

#  email                :string(255)     

class User < ActiveRecord::Base

 #...

end

只要在该类中加入以下代码,就可以在 validation 的错误信息中显示中文字段名:

 

humanize_attributes :login => "用户名",

                   :email => "电邮"

现在 Rails 2.2 为我们带来了强大的 I18N 功能,没有必要再用上述方法来实现本地化了。

首先,在 environment.rb 中指定本地化语言:

config.i18n.default_locale = :cn

然后在 config/locales 目录下新建 cn.yml 文件,并进行以下设置:

cn:

   active record:

       models:

           user: "用户"

       attributes:

           user:

               login:  "用户名"

               email:  "电邮"

非常优雅方便。

 

Error messages 也可以用同样的方法进行设置。比方说,以前会用:

 

validates_presence_of     :login, :message => "不能为空"

现在只要在配置文件中加入相应信息即可:

 

active record:

       errors:

           messages:

               blank:      '不能为空'

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。