0

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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.