Accessing a variable declared in another rb file

The best way to export data from one file and make use of it in another is either a class or a module.

An example is:

# price.rb
module InstancePrices
  PRICES = {
    'us-east-1' => {'t1.micro' => 0.02, ... },
    ...
  }
end

In another file you can require this. Using load is incorrect.

require 'price'

InstancePrices::PRICES['us-east-1']

You can even shorten this by using include:

require 'price'

include InstancePrices
PRICES['us-east-1']

What you've done is a bit difficult to use, though. A proper object-oriented design would encapsulate this data within some kind of class and then provide an interface to that. Exposing your data directly is counter to those principles.

For instance, you'd want a method InstancePrices.price_for('t1.micro', 'us-east-1') that would return the proper pricing. By separating the internal structure used to store the data from the interface you avoid creating huge dependencies within your application.


Declaring the variable inside a tiny and simple class would be the cleaner solution imho.

Tags:

Ruby