juan2raid
juan2raid

Reputation: 1644

Require statements inside methods?

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.

Upvotes: 20

Views: 4613

Answers (3)

Vaibhav Malushte
Vaibhav Malushte

Reputation: 171

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

Upvotes: 2

AboutRuby
AboutRuby

Reputation: 8116

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.

Upvotes: 20

seand
seand

Reputation: 5296

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.

Upvotes: 5

Related Questions