Authentication and Devise
One of the most basic feature of dynamic websites is user accounts. This lets people do things on the site and save information, something simple static sites cannot offer.
To enable user accounts, an application needs to let users register with a logon id (such as an email) and a password. Later, a user can use this information to sign in, and the application will check that the logon id and password match to authenticate the user.
Registration and authentication is complex, but the overall process is usually very similar on different websites, so it's a good process to 'outsource' to a gem. To find an authentication gem, let's Google it. The top result is from Ruby-Toolbox, and it lists multiple gems we could use.
The bar chart on the top shows the popularity of each gem, and below that is a list of the gems with more info and links. The first gem, devise, has over 1.1 million downloads and is quite popular on Github. You can tell that it's used by many people and is actively maintained, so it can't be a bad choice. Devise is actually a great choice if you want to get authentication set up quickly, want the option to add more features later, and are willing to go along with its default ways.
It can sometimes make sense to create your own authentication system from scratch, but we're not going to do that for a few reasons:
- speed - it's faster to use a gem than to hand-code it yourself, and our goal is to build an app quickly
- extendibility - if you want to add an authentication-related feature later (such as email confirmations or password resets), you'll need to hand-code it. Devise comes with modules to provide such features.
- security - if you mess up implementing your own authentication, user accounts on your site can get hacked. It's safer and easier to use a well-tested gem that's kept up-to-date and secure.
Once you found the gem to use it's time to add it to you gemfile.
Note: If you cloned the original Learneroo source project, your app may already include the devise gem in it. If that's the case, you don't need to add it again to your gemfile!
Go the Ruby gem page linked to from Ruby-Toolbox and copy the line with the gem and version, and paste it in your gemfile.
gem 'devise', '~> 3.4.1'
Gem version
You could just specify the gem name without a version (gem 'devise'
) and this will install the latest available version of the gem. If you're afraid that future gem updates may break your app, you can specify an exact version (gem 'devise', '3.4.1'
). Using a squiggly arrow ~>
is a recommended compromise. This means the gem will automatically be updated for small updates but you will need to manually change the version for larger "big number" updates.
Once you've added the gem name to your gemfile, run bundle install
in your terminal to install the gem.