开发者

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

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 pra开发者_开发知识库ctice 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.


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.


All of the ruby scripts i have seen just list one require per line like you have first.

require 'rubygems'
require 'rack'
require 'rails'


In the first one it is clear what you're doing.

In the second it requires someone to decode what you're doing.

It seems a bit whimsical to force everybody to decode what you're doing so you can save a few lines of typing (and that only if you're using a whole lot of libraries in one source file which is a bit of code smell in and of itself). Remember that code is read an order of magnitude or three times as often as it is written. If it's a choice between easy writing or easy reading, the reading should win out.


%w(rubygems rack rails).each { |gem| require gem }

or, with a reusable function:

def require_all(gems) ; gems.each { |gem| require gem } ; end
...
require_all %w(rubygems rack rails)

Neither is popular Ruby style (especially a one-liner function), but Ruby embraces TIMTOWTDI, so use them if they work for you.


This isn't the best, but if you do:

def require_all(*gems)
   g = *gems
   g.each {|gem| require gem }
end

Alternatively add this one-liner to the beginning of your code:

def require_all(*gems); g = *gems; g.each { |gem| require gem }; end

You can just pass multiple gems to require_all; e.g.

require_all 'rack', 'bundler', 'rails'

And so on. Got the idea from the above answer!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜