Ruby requires confusion

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值