Reputation: 7718
To load a Ruby file only if it is necessary, I did this in a project:
XController ...
...
if(!user.last_ip_country_id || user.last_login > Date.today - 1.week)
require 'ip_to_country.rb'
Thinking about how Ruby on Rails runs, does it make sense to do this? Should it be at the top? Or, is there any advantage for requiring a file only when needed (like lazy load)?
Upvotes: 1
Views: 68
Reputation: 168101
If that part of the code is executed once at the start, then it makes sense to do that. And in fact, there are authentic codes that do that. Typical examples are when you want to require different gems or local files depending on your environment.
Also when the file to be loaded has its own name space that does not interact with the other part of your code, then, you can do lazy loading at an arbitrary point in your code.
Otherwise, i.e, if that part of the code is executed repeatedly during use and the file to be loaded may interact with the rest of the code (such as by monkey patching common classes), then it is not a good idea to do that because it would be more difficult to consider the interaction of your code with the gem if it were loaded in the middle of the code at a specific timing.
Upvotes: 1