2016-08-01 2 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 ('') 및 클라이언트 = Aws :: S3 :: Client.new ('')를 정의하는 가장 좋은 장소는 무엇입니까? – Michael

+0

비밀 키를 보관할 수있는 가장 좋은 곳은'config' 폴더 안에있는 yml 파일입니다.이 파일을 사용하는 클래스는'initializers' 안에 있습니다. –

+0

'AwsS3Initalization'의 인스턴스를 생성해야합니까? 내 앱에 여러 개의 액세스 키가 있습니까? –

관련 문제