2016-08-01 16 views
0

メインクラスを1つ持ち、内部に他のクラスで呼び出す変数をいくつか入れたいと思います。例:異なるクラス間で変数を共有するRuby

class AwsS3Initalization 
    attr_reader :resource, :client 

    def initialize resource, client 
    @resource = resource 
    @client = client 
    # Where do I define those variables below? I think this is not the right place to put them 
    @resource = Aws::S3::Resource.new(region: 'region', access_key_id: 'my-key', secret_access_key: 'secret-key') 
    @client = Aws::S3::Client.new(region: 'region', access_key_id: 'my-key', secret_access_key: 'secret-key') 
    end 
end 

私が持っている他のクラスの@resourceと@clientを呼び出せます。これを行う最善の方法は何ですか?そして、あなたはサブクラスに親クラスからすべての変数にアクセスすることができます

class Foo < AwsS3Initalization 
end 

class Bar < AwsS3Initalization 
end 

答えて

0

最良の方法は次のようAwsS3Initalizationから他のクラスを継承することであろう。

UPDATE

class AwsS3Initialization 
    ACCESS_KEY = <read-from-yml> 
    SECRET_KEY = <read-from-yml> 

    def self.resource 
    Aws::S3::Resource.new(...) 
    end 

    def self.client 
    Aws::S3::Client.new(...) 
    end 
end 
+0

ありがとうございました!リソース= Aws :: S3 :: Resource.new( '')とクライアント= Aws :: S3 :: Client.new( '')を定義するのに最適な場所は何でしょうか? – Michael

+0

私の知る限り、あなたの秘密鍵を保持する最も良い場所は、 'config'フォルダ内のymlファイルで、' initializers'の内部にあるクラスを定義するクラスです。 –

+0

'AwsS3Initalization'のインスタンスを作成する必要がありますか?私はあなたのアプリでこれのための複数のアクセスキーがあるのですか? –

関連する問題