2014-10-10 44 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