Michael Michael - 4 months ago 32
Ruby Question

Share variables across different classes Ruby

I want to have one main class and inside it some variables that I want to call inside other classes. For example:

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


I want to be able to call @resource and @client in other classes that I have. What is the best way to do this?

Answer

Best way would be to inherit other classes from AwsS3Initalization like:

class Foo < AwsS3Initalization
end

class Bar < AwsS3Initalization
end

Then you will be able to access all the variables from parent class into subclasses.

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