문제

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