2016-08-01 111 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'的实例吗?我的意思是在你的应用程序中有多个访问键? –