Ruby on rails 在类名之前访问应用程序控制器变量

Ruby on rails 在类名之前访问应用程序控制器变量,ruby-on-rails,subdomain,Ruby On Rails,Subdomain,我想在另一个控制器的类名之前访问application\u controller变量 class TodosController < eval("#{subdomain_name.humanize}Controller") 类TodosController

我想在另一个控制器的类名之前访问
application\u controller
变量

class TodosController < eval("#{subdomain_name.humanize}Controller")
类TodosController

我想自定义我的
ToDoController
,以便为不同的子域继承不同的控制器。

只需使继承方法的实现依赖于子域即可

避免此类方法成为丛林的一种方法是使用单独的对象对子域特定的“策略”进行建模。下面是一个实现特定于子域的before过滤器的可能解决方案

class TodosController < ApplicationController

  before_filter :require_foobar_is_allowed

  # ...
end
然后在特定于域的策略对象(普通的旧Ruby对象)中定义实现,例如,
app/models/

class FoobarSubdomainPolicy
    def foobar_allowed_for?(user)
        # in the foobar subdomain, foobar is allowed for everyone
        true
    end
end

class BazSubdomainPolicy
    def foobar_allowed_for?(user)
        # in the baz subdomain, foobar is only allowed for admins
        user.admin?
    end
end

根据“继承的”功能的实际外观,gem中可能也存在现成的解决方案,例如designe。

而不是
eval
,您可能应该使用
“{something}Controller”。constantize
,但无论如何,这听起来是一个非常糟糕的主意。也许如果你更详细地描述了你想要实现的目标,有人会给你指出一个更好的解决方案。你不能这样动态地改变祖先,但是,您可以包括新的modules@oseiskar我正在使用子域路由,我希望通过在此处内置这些控制器来使用名为Todo的资源的所有筛选器和限制。如果我可以在这个区域类中访问我的应用程序控制器的任何变量,以访问控制器class FoobarSubdomainPolicy def foobar_allowed_for?(user) # in the foobar subdomain, foobar is allowed for everyone true end end class BazSubdomainPolicy def foobar_allowed_for?(user) # in the baz subdomain, foobar is only allowed for admins user.admin? end end