2016-08-01 66 views
0

我想要一個主類,裏面有一些我想在其他類中調用的變量。例如:在不同類中共享變量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。做這個的最好方式是什麼?

回答

0

最好的辦法是從AwsS3Initalization像繼承其他類:

class Foo < AwsS3Initalization 
end 

class Bar < AwsS3Initalization 
end 

然後,你將能夠訪問來自父類的所有變量到子類。

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('')和client = Aws :: S3 :: Client.new('')? – Michael

+0

據我所知,保存密鑰的最佳位置是'config'文件夾內的yml文件,並且使用它們定義一個類在'initializers'內部。 –

+0

您確定需要創建'AwsS3Initalization'的實例嗎?我的意思是在你的應用程序中有多個訪問鍵? –