[英]How to get the current instance module in Ruby
That title doesn't really explain everything so here goes. 该标题并不能真正解释所有内容,因此请继续。 I have two Rails engines that share some functionality (ie. user model and authentication).
我有两个共享某些功能(即用户模型和身份验证)的Rails引擎。 I have a base
User
class and then two other User classes that inherit from this base class for each app like so: 我有一个基本的
User
类,然后是从每个应用程序的该基本类继承的其他两个User类,如下所示:
class User; end
class App1::User < ::User; end
class App2::User < ::User; end
My authentication has a method similar to the following 我的身份验证具有与以下类似的方法
def user_from_session
User.find_by_id(session[:user_id])
end
which is included in my application_controller. 这包含在我的application_controller中。 My problem here is that when a user is fetched... it always uses the base
User
class. 我的问题是,提取用户时,它总是使用基本的
User
类。 What I really want is to be able to fetch a User that is the same type as the app calling that method. 我真正想要的是能够获取与调用该方法的应用相同类型的User。
For instance, if a user is on SomeController
: 例如,如果用户在
SomeController
:
class App1::SomeController < ApplicationController; end
I want the method in the application_controller to pull out the App1
so that it instantiates an App1::User
rather than just a User
我希望application_controller中的方法拉出
App1
以便它实例化一个App1::User
而不只是一个User
Is this possible? 这可能吗?
I'm NOT looking for a solution that involves two user_from_session
methods, one for each application. 我不是在寻找涉及两个
user_from_session
方法的解决方案,每个应用程序一个。 I am aware of how to implement that. 我知道如何实施。 I'm more interested in know if this type of thing is possible in Ruby.
我更想知道在Ruby中是否可以进行此类操作。
Though I'd caution you to find a better, less hacky way to do this, here's how you might do it: 尽管我会提醒您找到一种更好,更简单的方法来实现此目的,但是您可以按照以下方式进行操作:
def user_from_session
# App1::Whatever::FooController -> App1::Whatever
module_name = self.class.name.split('::')[0..-2].join('::')
# App1::Whatever -> App1::Whatever::User
user_class = "#{module_name}::User".constantize
# App1::Whatever::User.find_by_id(...)
user_class.find_by_id(session[:user_id])
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.