When to use `require`, `load` or `autoload` in Ruby?

前端 未结 4 950
死守一世寂寞
死守一世寂寞 2020-12-02 12:06

I understand the subtle differences between require, load and autoload in Ruby, but my question is, how do you know which one to use?

相关标签:
4条回答
  • 2020-12-02 12:29

    Generally, you should use require. load will re-load the code every time, so if you do it from several modules, you will be doing a lot of extra work. The lazyness of autoload sounds nice in theory, but many Ruby modules do things like monkey-patching other classes, which means that the behavior of unrelated parts of your program may depend on whether a given class has been used yet or not.

    If you want to make your own automatic reloader that loads your code every time it changes or every time someone hits a URL (for development purposes so you don't have to restart your server every time), then using load for that is reasonable.

    0 讨论(0)
  • 2020-12-02 12:33

    Apart from what others have already told you, future of autoload is uncertain. It was scheduled to be deprecated in Ruby 2.0, but the deprecation wasn't made in time for the 2.0 feature freeze. It is now expected that autoload will be deprecated in Ruby 2.1, but that is not even certain anymore.

    0 讨论(0)
  • 2020-12-02 12:39

    here's what you gain with autoload over require:

    autoload is primarily for speeding up the initialization phase of your Ruby program or Rails application. By not loading the resources until they are needed, it can speed up things quite a bit.

    Another advantage is that you may not need to load some parts of the code, if the user doesn't use certain features -- thereby improving load time and reducing the memory footprint.

    0 讨论(0)
  • 2020-12-02 12:44

    mylibrary.rb

    puts "I was loaded!"
    
    class MyLibrary
    end
    

    Try in irb

    irb(main):001:0> require 'mylibrary'
    I was loaded!
    => true
    
    irb(main):001:0> autoload :MyLibrary, 'mylibrary'
    => nil
    irb(main):002:0> MyLibrary.new
    I was loaded!
    => #<MyLibrary:0x0b1jef>
    

    See the difference.

    0 讨论(0)
提交回复
热议问题