Cole Bittel
Cole Bittel

Reputation: 2884

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

Upvotes: 1

Views: 501

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369420

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.

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 automatically load the whole standard library, this would incur unnecessary overhead for things you don't use.

  • 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.

Upvotes: -2

infused
infused

Reputation: 24337

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.

Upvotes: 2

Related Questions