tags:

views:

71

answers:

4

I am working on developing an API for a test suite. One of the methods in the API requires the use of a library that isn't needed anywhere else in the API.

My question is whether the require statement for using the library should be placed inside the method or every time the API loads. The library isn't very large so it won't have a significant effect on performance.

+3  A: 

I'd prefer putting the 'require' statement near the top of the file because when looking in the .rb it makes the dependencies clear. Similar to how .c files normally have all the #includes at the top.

seand
+4  A: 

If the dependency has good namespace organization (won't pollute the global namespace) and isn't large (won't slow startup times), I'd say put it at the top of the file. It's where people expect to find require statements. If it has either of those problems, consider putting it in the most limited scope possible.

AboutRuby
A: 

In Python, I've seen imports are used in mid-code, but mostly for conditional imports or handling import errors

http://diveintopython.org/file_handling/index.html#crossplatform.example

In Ruby, you cannot handle require errors:

begin
  require 'aaa'
rescue
  p "ERROR"
end
p "Hello, world!" # won't print

However, that's doesn't support the argument for loading modules mid-code. You should load the modules on the top of the file to keep track of them. Also, what happen if you are going to use the library code-wide in the future?

Imagine what happen if Java has imports inside blocks.

SHiNKiROU
You can absolutely handle require errors in Ruby. The reason your rescue doesn't work is that the default "rescue" only rescues StandardErrors, of which LoadError is not one. You just need to "rescue LoadError" instead.
Greg Campbell
+1  A: 

i will use require statement in method even if the file is small....

Vaibhav Malushte