Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to do multiple requires in Ruby?

Tags:

ruby

rubygems

I'm not sure I've seen this addressed, but I am wondering what is the best way to do multiple requires in a ruby script. I have come up with a couple rudimentary examples which I will outline below, but I'm not sure if there is a best practice for this -- my search results have come back with nothing.

0) Bunch of includes & exceptions (I'll leave the rescue out)

require 'rubygems'
require 'builder'

1) String array

torequire = ['rubygems', 'builder']
begin
  torequire.each do |req|
    require req
rescue LoadError => e
  # Not sure if this is great either
  puts "Missing required gem: " + e.message.split[-1]
  exit
end

2) ??

Is there a large problem created from loading them all from a string array? You could specify version requirements or locations similarly, I'm just wondering if there is a problem with doing it this way.

like image 739
alanp Avatar asked Feb 05 '11 02:02

alanp


People also ask

How require works in Ruby?

In Ruby, the require method is used to load another file and execute all its statements. This serves to import all class and method definitions in the file.

What is the difference between load and require in Ruby?

You should use load function mainly for the purpose of loading code from other files that are being dynamically changed so as to get updated code every time. Require reads the file from the file system, parses it, saves to the memory, and runs it in a given place.

How do I get the current directory in Ruby?

pwd : To check the current working directory, pwd(present working directory) method is used. 5. chdir : To change the current working directory, chdir method is used.

What does require do in rails?

require can also be used to load only a part of a gem, like an extension to it. Then it is of course required where the configuration is. You might be concerned if you work in a multi-threaded environment, as they are some problems with that. You must then ensure everything is loaded before having your threads running.


1 Answers

The plain way is the best way.

You could do this, but it trades clarity for cleverness--a poor bargain:

[
  'rubygems',
  'rack',
  'rails'
].each(&method(:require))

Skip the "rescue" with the fancy error message. Everyone knows what it means when a require throws a stack trace.

If you want to make it easier for someone using your program to have the required gems installed, check out bundler.

like image 147
Wayne Conrad Avatar answered Oct 16 '22 13:10

Wayne Conrad