简体   繁体   中英

Accessing a module/class with same name in a different file in ruby on rails

I am having 2 different file test1.rb and Report.rb as follows :

test1.rb

module List
 module Report
  constants = Report::Category.constants.collect{|c| c.to_s}
 end
end

In Report.rb

Class Report < ApplicationRecord
 module Category
  CONSTANT1 = 1
  CONSTANT2 = 2
 end
end

So I get an error in test1.rb saying undifined method category for list::Report. It is accessing the module list::Report insted for Report class from Report.rb. Is there a way to access another class/module with same name as the current file module?

Try

constants = ::Report::Category.constants.collect{|c| c.to_s}

(note :: before Report that causes constant's lookup to start looking from the outmost context)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM