【问题标题】:Is there a way to create temporary namespaces and constants in Ruby?有没有办法在 Ruby 中创建临时命名空间和常量?
【发布时间】:2013-01-02 19:03:59
【问题描述】:

我有一堂课:

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

我想创建一个进程来临时覆盖该类及其方法:

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)

Ruby 中有这样的东西还是我只是在做梦?无污染的命名空间、临时常量、方法、命名空间、类。干净、专注和优化的代码,没有太多干扰。

【问题讨论】:

    标签: ruby oop object object-oriented-analysis


    【解决方案1】:

    您可能正在考虑像Refinements 这样计划在 Ruby 2.0 中发布的东西。

    在那之前,你必须要有创造力。

    【讨论】:

    • 此Refinements 介绍的链接使这个答案成为一个被低估的宝石!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    相关资源
    最近更新 更多