开发者

How to get the current instance module in Ruby

That title doesn't really explain everyth开发者_Python百科ing so here goes. I have two Rails engines that share some functionality (ie. user model and authentication). I have a base User class and then two other User classes that inherit from this base class for each app like so:

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. My problem here is that when a user is fetched... it always uses the base User class. What I really want is to be able to fetch a User that is the same type as the app calling that method.

For instance, if a user is on 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

Is this possible?

I'm NOT looking for a solution that involves two user_from_session methods, one for each application. I am aware of how to implement that. I'm more interested in know if this type of thing is possible in 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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜