mamonas
mamonas

Reputation: 125

Why in Rails sometimes I need to require a package, and sometimes I don't?

I would like to know yhy in Rails sometimes I need to require a package, and sometimes I don't? Example:

class Visitor < ApplicationRecord
  validates :ipv4, allow_nil: true, format: { with: Resolv::IPv4::Regex, message: 'is an invalid IPv4' }
end

If I don't add require 'resolv' in the top of the file, I will have problems when calling the route that calls the controller that is using this model. The error will be:

#<NameError: uninitialized constant #<Class:0x0000555f53c743d8>::Resolv>

It seems totally arbitrary, although I now there must be some rule that of course I don't know.

Upvotes: 1

Views: 443

Answers (1)

Huy Ha
Huy Ha

Reputation: 179

It's all about autoload in Rails. By default you need to require the lib, but some gems put autoload to Rails so you don't need to require it when using.

https://www.rubyguides.com/2019/08/autoloading-in-ruby/

Upvotes: 3

Related Questions