Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require statements inside methods?

Tags:

ruby

require

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.

like image 533
juan2raid Avatar asked Aug 26 '10 23:08

juan2raid


People also ask

What is difference between require and include in Ruby?

The include and require methods do very different things. The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice.

Can you put a method inside a method in Ruby?

In short: no, Ruby does not support nested methods. Note also that in Ruby, method bodies cannot be closures, only block bodies can. This pretty much eliminates the major use case for nested methods, since even if Ruby supported nested methods, you couldn't use the outer method's variables in the nested method.

How does require work in Ruby?

Require reads the file from the file system, parses it, saves to the memory, and runs it in a given place. In require, if you modify the specified file when the script is running, those modifications won't be applied, Ruby will use the file from memory, not from the file system of the machine.

Where does Ruby look for require?

Ruby looks in all the paths specified in the $LOAD_PATH array.


1 Answers

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.

like image 74
AboutRuby Avatar answered Sep 22 '22 00:09

AboutRuby