2014-10-10 21 views
0

我有一个书面的一类:Rails的共享,在干燥方式使用method_missing的常量

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 

任何想法表示赞赏。提前致谢。

+0

你的意思是''“常量未定义:CONST [#{method_name}]”'? (我不知道Rails,所以我可能会错过一些东西。)为了可读性更好,考虑'..unless CONST.key?(method_name)'而不是'..if CONST [method_name] .nil?'。 – 2014-10-10 20:59:32

回答

0

我会使用子类和类方法,而不是一个实际的常量。

class ConstantAccessor 
    def self.method_missing(method_name, *args, &block) 
    super unless const[method_name] 
    const[method_name] 
    end 

    def self.respond_to?(method_name, include_private = false) 
    super unless const[method_name] 
    true 
    end 
end 

class State < ConstantAccessor 
    def self.const 
    @const ||= { 
     created: 0, 
     prepared: 1, 
     shadowed: 2, 
     vmxed:  3, 
     sbooted: 4, 
     booted:  5, 
     saved:  6, 
     dontknowen: 7 
    } 
    end 
end 

class AnotherSetOfConstants < ConstantAccessor 
    def self.const 
    @const ||= { 
     something: 0, 
     somethingelse: 1, 
     another: 2 
    } 
    end 
end 
+0

谢谢@Alex,这个作品完美! – Midwire 2014-10-11 14:42:49