简体   繁体   中英

When do I have to 'require' a Ruby class in my Rake task?

I'm working on a Rake task which fetches a file via an external URL. To do this, I have to require the Net::HTTP Ruby class in my .rake file.

This seems odd to me, because I've not loaded it in as a gem (I've not downloaded it from anywhere in fact), so this Ruby class must be pre-installed in the Rails framework. Yet in every .rake file I have, I have to require it. So it must, for some reason, be inactive until I tell it otherwise(?).

This is not the same question as "How to require classes that I've created in different files" . Rather, I want to know

  • How it is that I don't have to download and install the Net::HTTP class into my application?
  • Why do I have to manually require it when I use it, if it's already pre-installed in Rails?

Net::HTTP is part of the Ruby Standard Library , which is distributed with Ruby itself (not Rails). To use any of the standard libraries you must require them first.

I'm working on a Rake task which fetches a file via an external URL. To do this, I have to require the Net::HTTP Ruby class in my .rake file.

No, you don't. You don't require classes, ever. require loads files, not classes.

This seems odd to me, because I've not loaded it in as a gem (I've not downloaded it from anywhere in fact), so this Ruby class must be pre-installed in the Rails framework.

No, it isn't. It is a part of the Ruby standard library. You even linked to the documentation of the Ruby standard library!

Yet in every .rake file I have, I have to require it. So it must, for some reason, be inactive until I tell it otherwise(?).

Yes. Ruby doesn't magically require every Ruby file in the entire world. You have to require the files you need manually and explicitly.

  • How it is that I don't have to download and install the Net::HTTP class into my application?

Because the Net::HTTP class is defined inside the file net/http.rb , which is shipped as part of the Ruby standard library.

  • Why do I have to manually require it when I use it, if it's already pre-installed in Rails?

Because it's a Ruby file like any other Ruby file, and you need to tell Ruby which Ruby files you want to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM