سؤال

I have a class:

class MyClass
  def self.say_hello
    puts "hello"
  end
end

and I want to create a process to override the class and its method temporarily:

begin "a temporary namespace, constants, variables and methods within this code"
  Thread.current[:neverland] = -> do
    Object.instance_exec do
      class MyClass
        def self.say_hi
          puts "hi"
        end
      end

      MyClass.say_hi
      MyClass.say_hello
    end
  end
end

> Thread.current[:neverland].call
=> "hi"
=> "hello"

> MyClass.methods - Object.methods
=> ["say_hello"]

> MyClass.say_hi
=> undefined method `say_hi' for MyClass:Class (NoMethodError)

Is there something like this in Ruby or am I just dreaming? Namespace pollution-free, temporary constants, methods, namespace, class. Clean, focused and optimized code, without too much distractions.

هل كانت مفيدة؟

المحلول

You're probably thinking of something like Refinements that are scheduled for release in Ruby 2.0.

Until then you're going to have to be creative.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top