Ruby: import two modules / classes with the same name

When my system requires two classes or modules with the same name, what can I do to indicate what I mean?

I use rails (new to it), and one of my models is called "Thread". When I try to access the "Thread" class in thread_controller.rb, the system returns some other constant with the same name.

<thread.rb>
class Thread < ActiveRecord::Base

  def self.some_class_method
  end

end

<thread_controller.rb>
class ThreadController < ApplicationController

  def index
    require '../models/thread.rb'
    @threads = Thread.find :all
  end

end

When I try Thread.find (), I get a message that Thread does not have a named find method. When I turn to Thread.methods, I did not find among them some_class_method.

Any help? (And don't worry about publishing β€œjust call your model something else.” It's not useful to point out obvious trade-offs.)

+3
3

.

<my_app/thread.rb>
module MyApp
  class Thread
  end
end
+2

, - .

Thread Ruby , . Topic.

+2

, - :

# use Object to make sure Thread is overwritten globally
# use `send` because `remove_const` is a private method of Object
# Can use OldThread to access already existing Thread
OldThread = Object.send(:remove_const, :Thread)

# define whatever you want here
class MyNewThread 
  ...
end

# Now Thread is the same as MyNewThread
Object.send(:const_set, :Thread, MyNewThread)

, , Thread, , - .

, , , . , , "" .

+2

Source: https://habr.com/ru/post/1775091/


All Articles