Using Libraries

Learn about Ruby libraries and how to use them.

Our Person class doesn’t define an attribute accessor method for its password, and therefore, others can’t ask for and retrieve it.

However, our person object could freely give them an encrypted version of it.

This is pretty similar to how authentication often works in real web applications:

Applications don’t store our actual password in plain text (hopefully). That way, if they get hacked, attackers wouldn’t have our actual password. Instead, they store an encrypted version of the password.

We now want to add an encrypted_password method to the Person class. The method should return an encrypted version of the password that’s stored in the @password instance variable.

Encryption is one of the things in programming that requires very deep expert knowledge, and it’s one of the things we definitely wouldn’t want to implement ourselves.

Introducing libraries

So far, all Ruby features and methods that we’ve used are available right away when the Ruby runtime, ruby, executes our code. However, Ruby also comes with a ton of functionality that’s not available (loaded) right away. Instead, it’s stored in so-called libraries (just Ruby files too), and we have to load them manually to make them available.

The require method

To do this, we use the require method and pass it the name of the library:

Press + to interact
require 'digest'

Normally, require statements should be placed at the very top of the file so it’s easy to see what libraries a particular piece of code (class) uses.

In the following example of a Person class that we defined earlier, we’ve added a new method, encrypted_password:

Press + to interact
require 'digest'
class Person
def initialize(name)
@name = name
end
def name
@name
end
def password=(password)
@password = password
end
def encrypted_password
Digest::SHA2.hexdigest(@password)
end
end

The digest library that we required includes something called Digest::SHA2.

The digest library

A digest is an algorithm to convert one string into another so that the original string can’t be recovered later. However, digesting the same string always results in the same other, unique string. There are many algorithms that do this, such as sha2.

For our example here, we only need to understand that once we have required the digest library, we can use the Digest::SHA2.hexdigest method, and it will encrypt (digest) the string that we pass to it.

What if we now run the following code?

Press + to interact
person = Person.new("Ada")
person.password = "super secret"
puts person.encrypted_password

It outputs:

eabd522910ccdd77aef079feff0c7bb6486f6ab207ae6d3ed9e671208c92ab0f

This is the digested form of the "super secret" string. Every time we run the program, we’ll see the same unique string.