I have a model named Promotion.
class Promotion < ActiveRecord::Base;
FORMATS = [0,1]
end
I also have another subclass named ‘Promotion’ defined in a file in the /lib folder of my app.
module Faker
module MyProject
module Promotion
def format
# Need to access Promotion::FORMATS
end
end
end
end
I need to reference a constant defined in the AR class from within the other module. The only way I’ve been able to do it so far is to use
ActiveRecord::Base.descendants.detect{|model| model.name == 'Promotion'}::FORMATS
I’m wondering if there is a better way to go about this?
CORRECTION
Turns out that only worked from the command line. When I applied it to the Promotion submodule, it didn’t return the same list of models. So rather than a better way, what is the way to access an AR model in a non-ambiguous way? I’ve updated the definitions above to better illustrate what I’m trying to do.
This is a question of how constants are scoped.
The simple answer is
In your example
Promotion has been defined on the global scope so can be accessed in 3 ways
But within your module
Faker::MyProjectany reference toPromotionwill look up this namespaceIf
Faker::MyProject::Promotionexists it’ll return this.I suggest you make a habit of refering to
::Promotionin these type of cases.Example: