How can I disambiguate my own class from a gem's class

Viewed 124

I have a Rails project that I have been working on for a while. Like many Rails projects I have a User class. In one of my controllers I need to access some methods from a gem I am using. The example code from the gem demonstrates using an include to a particular gem module. I'm not going to use the actual gem here because it is not important to the question. I have no control over this gem and I need functionality from the module.

include GemName::Module

The problem is that the Gem includes its own User class directly under the module I have included in my controller. This results in calls to my own User class to methods not defined in the gem's user class failing:

User.working?(:test_user)

NoMethodError (undefined method `working?' for GemName::Module::User:Class):

What I would like to do is be able to include the module in my controller and be able to use my application's User class in that same controller.

I have tested the following workarounds, both of which seem to work, neither of which I am particularly happy with:

  1. Create a new constant to refer to my own user class before including the gem module.
LocalUser = User
include GemName::Module
  1. Do not include the module and explicitly call any classes I may need with the fully namespaced call.
GemName::Module::Class.method

I realize I could namespace my User class but that would involve a lot a refactoring around my codebase and I don't really love the idea anyway. This controller calls classes from the gem about 20 times and my own User class exactly once. The controller never calls the gem's User class. If possible, I'd love to force the call to my own User class to refer to the my non namespaced class explicitly and keep the include to the gem module.

Hopefully there is an elegant solution which will increase my understanding of namespaces in Ruby

1 Answers

Just after posting the question, I thought "What if I simply add :: in front of User when calling my own non-namespaced class?"

Sure enough, it works.

::User.working?(:test_user)

Calls my own User class.

I'm leaving the question and this answer up in case it helps others.

Related