我写了一堂课:
module SharedConstants
class Stage
CONST = {
created: 0,
prepared: 1,
shadowed: 2,
vmxed: 3,
sbooted: 4,
booted: 5,
saved: 6,
dontknowen: 7
}
def self.method_missing(method_name, *args, &block)
fail "Constant not defined: #{name}.#{method_name}" if CONST[method_name].nil?
CONST[method_name]
end
def self.respond_to?(method_name, include_private = false)
CONST[method_name].nil? ? super : true
end
end
end
...当我们想要访问这样的常量时,这非常有用:
Stage.created # => 0
现在我想介绍另一组名为 Foo 的常量,但我想干掉代码。
我试图将这两个类方法移入 SharedConstant 模块并“扩展”该模块。尝试创建一个“基础”类并从中派生,但我无法获得任何工作方法。
这是我的规格示例:
require 'rails_helper'
RSpec.describe SharedConstants::Stage, type: :lib do
[:created, :prepared, :shadowed, :vmxed, :sbooted,
:booted, :saved, :dontknowen].each do |const|
it "defines #{const}" do
expect(described_class.send(const)).to be >= 0
end
it "responds to #{const}" do
expect(described_class.respond_to?(const)).to eq(true)
end
end
end
任何想法表示赞赏。提前致谢。