简体   繁体   English

如何“继承” ApplicationController中的类变量

[英]How to “inherit” a class variable from ApplicationController

I'm a little new to rails. 我是Rails的新手。

Say I want to do something like: 假设我想执行以下操作:

def is_admin?
 @admin = User.grab(session[:username]).admin
end

I can define this in the ApplicationController but then I have to call is_admin?() in every method in every subsequent controller. 我可以在ApplicationController中定义它,但随后必须在每个后续控制器中的每个方法中调用is_admin?() Is there a way around this that I am not aware of? 有没有办法解决我不知道的问题?

Use a :before_filter at the start of each controller: 在每个控制器的开始处使用:before_filter

before_filter :is_admin

At least then you don't have to do it for every method. 至少您不必为每种方法都这样做。

I'm not sure exactly what the problem with calling is_admin? 我不确定调用is_admin?到底出了什么问题is_admin? is. 是。 Calling methods in Ruby is pretty cheap. Ruby中的调用方法非常便宜。 You may want to "memoize" the return value to avoid calling to the database every time the method is called: 您可能需要“记住”返回值,以避免每次调用该方法时都调用数据库:

def is_admin?
  unless defined?(@is_admin)
    @is_admin = User.grab(session[:username]).admin
  end

  @is_admin
end

Since is_admin? 由于is_admin? can return a falsey value, ||= won't work. 可以返回假值, ||=将不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Rails 3.2 ApplicationController如何继承模块ApplicationController - Rails 3.2 ApplicationController how to inherit modules ApplicationController 如何在Rails 4中不从ApplicationController继承时包含respond_to? - How to include respond_to when you don't inherit from ApplicationController in Rails 4? 如何将一个助手从ApplicationController包含到Sidekiq worker中? - How to include a helper from the ApplicationController into a Sidekiq worker? 如何从 ApplicationController (Rails) 访问 cookie - How to access cookies from ApplicationController (Rails) 如何从ApplicationHelper调用ApplicationController方法 - How to call ApplicationController methods from ApplicationHelper 如何从其他控制器调用ApplicationController中的方法? - How to call methods in ApplicationController from other controllers? 如何访问在序列化器内部的 ApplicationController 中定义的@current_user 变量 - How to access @current_user variable defined in ApplicationController inside of Serializer 从ApplicationController渲染部分 - Render partial from ApplicationController 来自ApplicationController的访问方法 - Access method from ApplicationController 如何确定已从ApplicationController调用了哪个控制器? - How to determine which controller has been called from ApplicationController?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM