开发者

Rails 3: Dynamically set after_filter in before_filter?

I would like to define an after_filter to restore the changes of my before_filter, such that the changes made only affect that one action in my controller. Here's what I have so far:

before_filter :exclude_root_in_json
after_filter :restore_root_in_json

def exclude_root_in_json
  ActiveRecord::Base.i开发者_开发百科nclude_root_in_json = false
end

def resotre_root_in_json
  ActiveRecord::Base.include_root_in_json = true
end

Is there any way I can do something like the following?

def exclude_root_in_json
  default = ActiveRecord::Base.include_root_in_json
  ActiveRecord::Base.include_root_in_json = false
  self.class.after_filter do
    ActiveRecord::Base.include_root_in_json = default
  end
end

My end result is to end up with a before_filter call that automatically undoes the changes for that one particular action once that action is completed. How would I do this?


Sounds like you might be able to use an around_filter. Check out this page of the api docs:

http://rails.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html

Try it like so:

around_filter :exclude_root_in_json

private
  def exclude_root_in_json
    default = ActiveRecord::Base.include_root_in_json
    ActiveRecord::Base.include_root_in_json = false
    yield
    ActiveRecord::Base.include_root_in_json = default
  end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜