How to define an application-level global method to be used anywhere in Rails?

Viewed 185

I have a method current_org that's defined simply as:

def current_org
  Organization.find_by(subdomain: Apartment::Tenant.current)
end

It's always the same, whether it's in a view, controller, a model, or even a service. Since the current tenant is derived from the database connection, I shouldn't have to worry about it being properly scoped. And I find myself using it everywhere.

What's the best way to define a global method in Rails so I can just call current_org from anywhere? Currently my best solution is defining a module in /lib and calling it with CustomHelperMethods.current_org. But I'm looking for something a little cleaner.

1 Answers

I'd put it as a class method in an Organiation model or create a special service/class that fetches it.

class Organization < ApplicationRecord
  def self.current_org
    find_by(subdomain: Apartment::Tenant.current)
  end 
end

or

# e.g. in app/services/
class CurrentOrganization
  def self.current_org
    Organization.find_by(subdomain: Apartment::Tenant.current)
  end 
end
Related