Reputation: 1696
I thought I understood the difference between require
and include
with the help of this this thread.
Then I stumbled on this piece of code from the github page of the bcrypt-ruby gem. Why are they using both methods? So first single models are going to be loaded but then again through include
all the functions?
require 'bcrypt'
class User < ActiveRecord::Base
# users.password_hash in the database is a :string
include BCrypt
.....
Upvotes: 0
Views: 685
Reputation: 2450
require
loads a ruby file, making the BCrypt module available to your ruby code. It does not, necessarily have to be in the same file as the class you're including the module in.
require
can also be used to make a ruby class defined in that file available (for instance, other classes you've defined in your project). As it's in a gem, bcrypt is on the ruby path, if it's a file in your project you may need to reference the full path, or use require_relative
.
include
takes the code in the bCrypt module and includes it to your User class, providing User with the methods and attributes declared in the BCrypt module.
Upvotes: 4
Reputation: 160170
require
loads the class.
include
actually puts it inside the User
class, e.g., including the module's methods as part of the definition of the User
class.
The question you reference is pretty explicit about the difference.
Upvotes: 3