Ruby is already using the class name of my model

后端 未结 3 1789
攒了一身酷
攒了一身酷 2021-01-07 01:46

I\'m making a forum application with various levels of authorization, one of which is a Monitor. I am doing this by extending my User class, and I plan on fine tuning this

相关标签:
3条回答
  • 2021-01-07 02:04

    Declare your Monitor class in other module.

    module MyModule
    
      class Monitor
    
      end
    
    end
    
    0 讨论(0)
  • 2021-01-07 02:04

    FYI, I just found a neat trick (errr, hack) to get around this which may work.

    I work on a large legacy application which, unfortunately, has a "Fixture" model which is quite important and which is used everywhere. When running tests, it's impossible to create a Fixture instance because of the Fixture class used by ActiveRecord when running tests. So I did the following:

    FixtureModel = Fixture.dup
    

    This freezes my class in place so that I can refer to it later (but just in my tests!) without being extended by the ActiveRecord Fixture class (which is not namespaced)

    0 讨论(0)
  • 2021-01-07 02:09

    Some possibilities:

    • avoid the require 'monitor.rb' call which is pulling in the standard Monitor instance
    • do some runtime magic to rename the existing Monitor class.
    • monkey with your load path so that require 'monitor.rb' pulls in an empty implementation of Monitor.

    But in all cases you could end up with the situation where a 3rd party library is using Monitor expecting it to be the standard Monitor class. So, I'd advise against any of the above.

    I'd say your only two reasonable options are:

    A) you could put your class in a namespace:

    Module MyApp
      class Monitor
        #...
      end
    end
    

    if your app uses some kind of auto-require magic (e.g it's a rails app) then you would put your implementation in /my_app/monitor.rb. When you wanted to refer to that class you would do something like my_monitor = MyApp::Monitor.new(), or whatever.

    B) you could use a different class name :)

    0 讨论(0)
提交回复
热议问题