2016-04-27 1 views
5

私はそれらに含まれているモジュールで、さまざまなクラスの中で保持されている定数にアクセスしようとしています。モジュールのためのロジックが複数のクラス間で共有されたように基本的な例Ruby:クラスから定数にアクセスする方法モジュールが含まれています

module foo 
    def do_something_to_const 
    CONSTANT.each { ... do_something ... } 
    end 
end 

class bar 
    include foo 

    CONSTANT = %w(I want to be able to access this in foo) 
end 

class baz 
    include foo 

    CONSTANT = %w(A different constant to access) 
end 

として、私はただの定数(各クラスで同じままその名前が、その内容を参照できるようにしたいと思います変化する)。私はこれをどうやって行っていくのですか?

答えて

3

あなたは、後者はわずかに速いことで、self.classように含まれるクラスモジュールと使用const_getまたは単にself.class::CONSTを参照できる:

module M 
    def foo 
    self.class::CONST 
    end 
end 

class A 
    CONST = "AAAA" 
    include M 
end 

class B 
    CONST = "BBBB" 
    include M 
end 

puts A.new.foo # => AAAA 
puts B.new.foo # => BBBB 
+1

ありがとうございました@Vasfedそれは私たちが探していたものです。 –

+0

反射を使う必要はありません。 'self.class :: CONST'をリフレクションなしで使うこともできます。 –

+0

@JörgWMittagあなたが正しいです、それは約2-9%速く、更新された答えです – Vasfed

0

::演算子を使用して、範囲CONSTANTからBARまでをスコープできます。構文は次のようになります。

module Foo 
    def do_something_to_const 
    Bar::CONSTANT.each { |item| puts item } 
    end 
end 

class Bar 
    include Foo 

    CONSTANT = %w(I want to be able to access this in foo) 
end 

Bar.new.do_something_to_const # outputs each item in Bar::CONSTANT 

これを避けようとします。含まれるモジュールは、それが含まれているクラスの実装の詳細を知る必要はありません。

+0

とクラスを参照することができますここでの問題は、モジュールが実装されていることをモジュールが知ってはならないことです。私は多くのクラスで同じモジュールを使用していますので、そうすることはできません。 元のコードサンプルを拡張して明確にします。 –

1

をあなたがself.class

module Foo 
    def do_something 
    self.class::Constant.each {|x| puts x} 
    end 
end 

class Bar 
    include Foo 
    Constant = %w(Now is the time for all good men) 
end 

class Baz 
    include Foo 
    Constant = %w(to come to the aid of their country) 
end 

bar = Bar.new 
bar.do_something 
=> 
Now 
is 
the 
time 
for 
all 
good 
men 
=> ["Now", "is", "the", "time", "for", "all", "good", "men"] 

baz = Baz.new 
baz.do_something 
=> 
to 
come 
to 
the 
aid 
of 
their 
country 
=> ["to", "come", "to", "the", "aid", "of", "their", "country"] 
関連する問題