1

I have different definitions of a module in 3 different files and I want to load them dynamically depending on user interaction. Using Kernel.load() method only works successfully for me the first time a certain file loads. Does anyone know which method should I use to make a file load always, not regarding if it had been already loaded before?

The module contains some constants that are used in other parts of the application. Depending on user choice, one concrete module with specific values for that constants should be loaded so they will have the appropriate values.

4

1 回答 1

0

Most likely, you are not taking the right approach to your problem.

Why to define the same module differently if you can define many different modules with the same API and use the one you wish dynamically?

What are you doing with the module?

Are you using as a mixin?

if condition
  object.extend Module1
else 
  object.extend Module2
end
object.method(bla,blabla)

Are you just invoking its methods as static methods?

module = if condition
    Module1
  else
    Module2
end
module.method(bla, bla bla)

Instead of using constants you should use either static methods or a static method returning an hash with the value of your "constants". Constants are not very pratical.

Given that you want to use the modules to store data instead of logic, maybe you should use classes instead:

class Options
  attr_reader :constant_1,:constant_2
end

class Options1 < Options
  def initialize
    @constant_1="value1"
    @constant_2="value2"
  end
end

class Options2 < Options
  def initialize
    @constant_1="value3"
    @constant_2="value4"
  end
end

options= condition ? Options1.new : Options2.new

options.constant_1 # => intended value
于 2011-11-21T16:03:11.703 回答