Skittles
Skittles

Reputation: 2918

Ruby load/require files

What I'm attempting to do in Ruby is the equivalent to PHP's include or require statement.

In PHP, when you include or require a file, any PHP code in the included file is executed and globally scoped variables can be used in the file that houses the include.

In Ruby, I have this code;

# include file snippet
config = {'base_url' => 'http://devtest.com/'}

# main file
Dir.foreach(BASE_ROOT_PATH + 'config') do |file|
  if !(file == '.' || file == '..')
    filepath = BASE_ROOT_PATH + 'config/' + file
    load filepath
  end
end

config.inspect

The problem I'm encountering is that when I run the main file, it always errors out with this error;

/home/skittles/devtest/bootstrap.rb:24:in `<top (required)>': undefined local variable or method `config' for main:Object (NameError)
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from index.rb:27:in `<main>'

I know that it's pulling in the file because it's not throwing any errors. I tried load & require, both with the same error. I tried config.inspect and puts config, still same error.

It's almost like the included file is not executing the code inside it. Is that what's going on or am I simply doing something wrong?

Thanks

Upvotes: 1

Views: 1248

Answers (1)

Frederick Cheung
Frederick Cheung

Reputation: 84114

config isn't a globally scoped variable - it's a local variable and local variable scope does not stretch across a require or load.

If you did want a global variable then you need to call it $config - the prefix denotes whether a variable is local (no prefix), global ($) or an instance variable (@). A constant might also be appropriate.

Upvotes: 2

Related Questions