Ruby on Rails before_filter 与 ruby​​ 的初始化 [英] Ruby on Rails before_filter vs ruby's initialize

查看:27
本文介绍了Ruby on Rails before_filter 与 ruby​​ 的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我脑子里只有一个想法.下面有什么区别

Just a thought in my mind. what is the difference the following

before_filter

class ApplicationController < ActionController::Base
  before_filter :foo
  def foo
    @mode = Model.new
  end
end

ruby 初始化

class ApplicationController < ActionController::Base
  def initialize
    foo
  end

  def foo
    @mode = Model.new
  end
end

  1. ruby 的 initialize 方法在 rails 中是否按预期工作?
  2. 如果是,那么我们可以就地使用 initialize 过滤器必须应用于控制器中的所有操作吗?

推荐答案

对于每个请求,您确实会获得一个 ApplicationController 的新实例,但这里最大的禁忌是您正在尝试在不调用父行为的情况下覆盖 ActionController::Base#initialize 的核心行为.

For each request, you do get a fresh instance of ApplicationController, but the big no-no here is that you're attempting to override core behavior of ActionController::Base#initialize without calling the parent behavior.

ApplicationController < ActionController::Base

  def initialize
    super # this calls ActionController::Base initialize
    init_foo
  end

  private

  def init_foo
    @foo = Foo.new
  end
end

虽然这不是惯用的 Rails 行为.他们给你 before_filter 是有原因的;所以使用它.

This is not idiomatic Rails behavior though. They give you before_filter for a reason; so use it.

这篇关于Ruby on Rails before_filter 与 ruby​​ 的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆