When writing code that only uses rails * use autoload :ClassName, relative_path * this is okay since rails makes autoload not broken, and lazy loading is good. * otherwise, autoload isn’t threadsafe and should not be used
Else
in a gem or library that is in the load path, (e.g. lib)
use vanilla :require since in all rubies the argument will searched for via the load paths. e.g. require ‘foo/bar’ in lib/foo.rb and in lib/foo/bar.rb use require ‘bar/baz’ to require ‘lib/foo/bar/baz.rb’
to achieve lazy loading, put the require statement in a method or block to be evaluated when needed
using :require_relative can speed up require time as it essentially uses the absolute path (equivalent to File.expand_path("…/#{argument}", FILE)
some prefer library authors not use require_relative since it makes it impossible to mock/override the require in the test environment by manipulating the load path order. e.g. $:.unshift ‘.’; require ‘foo_gem’
avoid using require File.expand_path(’…/foo’, FILE) for the above reason
others prefer :require_relative whenever possible as it is faster https://rubyforge.org/pipermail/rspec-users/2011-November/020760.html
in your own codebase e.g. your web app
:require_relative is usually the better route, even in rails.
beware that it doesn’t work for evaluated (e.g. rack) apps https://gist.github.com/tjsingleton/5957780
Ruby requires confusion
最新推荐文章于 2024-08-22 21:44:44 发布