RUBY中重新定义常量(redefine constants in Ruby)

有个需求: 生产环境中的代码, 有一个常量。
但是需要在测试环境中修改它,把它从一个真正的对象变成mock object.

(提示:核心方法: const_set, const_defined? , remove_const )

所以搜索了一下,有这个文章:
( [url]http://stackoverflow.com/a/3377188/445908[/url] )

先定义这个module
module RemovableConstants

def def_if_not_defined(const, value)
self.class.const_set(const, value) unless self.class.const_defined?(const)
end

def redef_without_warning(const, value)
self.class.send(:remove_const, const) if self.class.const_defined?(const)
self.class.const_set(const, value)
end
end

然后就可以调用它了:
class A
include RemovableConstants

def initialize
def_if_not_defined("Foo", "ABC")
def_if_not_defined("Bar", "DEF")
end

def show_constants
puts "Foo is #{Foo}"
puts "Bar is #{Bar}"
end

def reload
redef_without_warning("Foo", "GHI")
redef_without_warning("Bar", "JKL")
end

end

a = A.new
a.show_constants
a.reload
a.show_constants


运行结果:
[quote]Foo is ABC
Bar is DEF
Foo is GHI
Bar is JKL[/quote]

下面是我自己的代码:

class Apple
COLOR = "red"
end

puts Apple::COLOR
puts "const_defined? #{Apple.const_defined?("COLOR")}"
Apple.send(:remove_const, 'COLOR')

# 三种不同的方法,都是定义常量
Apple.class_eval { COLOR = "yellow" }
#class Apple; COLOR="yellow" ; end
#Apple.const_set("COLOR", "green")
puts Apple::COLOR


运行结果:

[quote]red
const_defined? true
yellow
[/quote]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值