I have a directory full of ruby scripts for common tasks, and I’ve started to accumulate a set of common variables and methods that I find myself defining in each new script. The next step in improving this would seem to be creating a file (say, commonstuff.rb) and “require”ing that file from the other scripts so that the common variables and methods are all available everywhere and defined only once.
A simple attempt that didn’t work:
commonstuff.rb
username=ENV['USER']
home_dir_path=ENV['HOME']
def print_and_execute(command, &block)
puts command
process_io = IO.popen(command + "2>&1")
while(line=process_io.gets)
if (block != nil)
yield line
else
puts line
STDOUT.flush
end
end
end
script1.rb
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/common_stuff'
puts home_dir_path # Fail
print_and_execute "date" # Fail
I’ve used ruby libraries and frameworks, but I don’t have any of that available in my current environment. I just have straight ruby, and I’m a little rusty on some of the basic idioms that would work well here, or that would look right to a ruby expert.
Any help appreciated!
Wrap your methods and variables in a module, e.g.
Then script1.rb might be like:
Or, if you don’t want to include the module in your namespace:
See also Modules and the Programming Ruby page on modules.