Ruby on Rails – ODIN Project – 1

odinRuby on Rails

Now that you’ve got a good grounding in Ruby, it’s time to put that to work by learning how to rapidly develop websites using Ruby on Rails and be able to build and deploy a real website with confidence.

In this course, you’ll be doing a whole lot of building, each project a bit more advanced than the previous one. You’ll build about a dozen Rails projects from scratch, including one full-featured tutorial that we’ll be following along with as we go and a full scale web application of your own. More importantly, you’ll learn how to deconstruct a website into its underlying data architecture and then build an application around that. By the end of it all, you’ll have the confidence to put up a simple website in under an hour.


Introduction to Rails

Step 1: How this Course Will Work

You should already have a good idea of what Rails is all about after covering it in previous lessons . At this point, it’s time to take that theoretical knowledge and start building websites.

After each lesson or two, you’ll be asked to build one or more independent projects utilizing the concepts that were just covered. You’ll also be asked to complete a chapter or two from the Ruby on Rails Tutorial (https://www.railstutorial.org/book) by Michael Hartl.

That tutorial is often too deep for fresh beginners to Rails but we’ll be using it as way to build a single large project one chapter at a time while you progress through the lessons. You should have a much better idea of what’s going on in the tutorial than your average beginner since we’ll be covering each of its component concepts prior to actually building it in the tutorial.


The Roadmap

We’ll be starting with an overview of important topics like HTTP, MVC, REST, APIs, Cookies and Authentication.

We’ll move front-to-back, starting with the routing layer and moving into controllers and views so you can build a functional interface for your data. Next you’ll learn about storing and finding data in databases with SQL then how to turn that SQL into ActiveRecord queries. We next cover web forms, an area that has a lot more going on behind the scenes than you might expect, and authentication, which is essential to securing your application. We’ll cover some other intermediate topics like state and the asset pipeline to round out your initial understanding of Rails.

But we can’t stop there, so we’ll get back into ActiveRecord to give you the tools to really manipulate your data, as well as the knowledge of the forms that is required to bring that advanced functionality to the User. This is the really important side of Rails.

Finally, we’ll cover additional useful topics like how to send emails from your application, building and interfacing with APIs, design patterns, meta-programming and advanced routing before having you build your final project.


 Our Tools and Texts

The most important resources that we’ll leverage are the Rails Guides (http://guides.rubyonrails.org/) and the Ruby on Rails Tutorial (https://www.railstutorial.org/book) by Michael Hartl. Together, they comprise a near-complete set of open-source resources for learning Rails.

The Guides are comprehensive, basically a completely open-source textbook and reference manual for Rails. At times they’ll get a bit more technical than you might like, and it may be OK to skim some of that.

The Ruby on Rails Tutorial (https://www.railstutorial.org/book) by Michael Hartl is another open source resource which builds (over several hundred pages) a full featured web application (Twitter clone), including introducing you to testing your code using RSpec along the way.

A ‘typical’ workflow:

  1. I know I want to implement a feature… Google search to see if anyone implemented the same feature. Land on a Stack Overflow post that describes how to implement a similar feature.
  2. The SO post shows me the right direction to take, so I Google for the specific method it mentioned that I don’t understand. I end up on the Rails Guides page that talks about it.
  3. I pull up my completed version of the Rails Tutorial to make sure I’ve got the syntax correct and possibly to help write tests while I implement the feature.

As you can see, I frequently relied on the main resources you’ll be learning from and you’ll find them to be helpful long after you’ve completed this course, so it makes sense to get familiar with them!


Prerequisites

If you haven’t completed these, be sure to do so before getting started:


Additional Resources


Project: Getting Your Feet Wet With Rails

This will give you the chance to build a full Rails app using some of the special tools Rails provides.


Warmup: Installations and Blogger

You must have Rails and several other technologies properly installed on your computer. That will be the first task if you haven’t done so already.


Your Task

1. Verify that you’ve got Rails 4 and Ruby 2 working properly.

2. Look at the Web Development Frameworks section (See http://bedford-computing.co.uk/learning/ruby-on-rails/web-development-101-odin-project-2/)


 Project: Starting The RoR Tutorial

We will be using the Ruby on Rails Tutorial (https://www.railstutorial.org/book) by Michael Hartl. It is a complete, step-by-step walk-through of building and testing a Twitter-like micro-blogging application. It covers a lot of material  so we’ll be spacing out the chapters along the way to go with the appropriate lesson material.

Though this tutorial is a major common theme across all the coming lessons and serves to tie them together into one major project, we’ll also be building plenty of independent projects along the way.

In this chapter, you’ll build a simple scaffolded app on Rails. It won’t be as complicated as the BloggerTutorial was and is really just to make sure your system is all set up and your brain is switched into Rails mode.


 Your Task

1. Read and follow along with Chapters 1 and 2 of the Ruby on Rails Tutorial (https://www.railstutorial.org/book) by Michael Hartl, where you will create two basic Ruby on Rails applications. Michael takes steps to standardize the development process by partnering with Cloud 9 (https://c9.io/). Michael also favours Bitbucket (https://bitbucket.org/) over Github. If you choose to use Bitbucket keep in mind that your solution will not be viewable unless you make the repository public.


 Additional Resources

Look at {cl} Codelearn’s How to design a Rails app (http://www.codelearn.org/ruby-on-rails-tutorial/design-rails-app)


Step 2: A Railsy Web Refresher

Web Refresher and More

Introduction

To really understand how Rails works, you need to have a solid base of the workings of the web.


HTTP

HTTP is just a way of structuring the request-and-response conversation between your browser and the server. Actually, it’s not even a conversation since it is stateless… it’s more of an “ask and receive”. The protocol outlines how that brief piece of dialogue should occur.

One key component to pay attention to is the fact that the request and response both have header and (usually) body components. The header contains information about the request or response itself (meta data), including which website to send or return to and what the status of the response is. The body of the request can contain things like data submitted by a form or cookies or authentication tokens while the response will usually contain the HTML page you’re trying to access.

The other key component is that each request uses one of four main “verbs” — GET, POST, PUT, and DELETE. These days, you almost only see GET and POST requests (even if you’re trying to do a delete of something they usually fake it using a POST request), but it’s important to understand the difference between the verbs.


REST

REST is a term that you’ll see coming up again and again because it’s a very powerful idea. It basically says that there are really only 7 different types of things that you usually want to do to an individual resource via the web and you can do them by mixing and matching the HTTP verbs we just covered. A “resource” usually means a “thing” in your database or a data model. In this case, we’ll assume that resource is a blog Post model that you’ve set up:

1. GET all the posts (aka “index” the posts)

2. GET just one specific post (aka “show” that post)

3. GET the page that lets you create a new post (aka view the “new” post page)

4. POST the data you just filled out for a new post back to the server so it can create that post (aka “create” the post)

5. GET the page that lets you edit an existing post (aka view the “edit” post page)

6. PUT (or PATCH) the data you just filled out for editing the post back to the server so it can actually perform the update (aka “update” the post)

7. DELETE one specific post by sending a delete request to the server (aka “delete” the post)

Why is this important? Because it gives you a very organized way of thinking about your resources. This is the way to model your requests and should be the ONLY way that those requests are done (ie. you shouldn’t be actually submitting the data for editing a post using a GET request -it should be a POST). If you have a hard time thinking of how those seven scenarios (or at least a subset of them) would apply to a resource you want to create in your database, you may need to rethink how your data is being set up.

It’s also important because Rails is structured to follow these conventions in a very straightforward way. As long as you’re performing those actions, life is very easy for you and the request that you get from the browser can be easily routed through Rails.

It may seem simplistic to you up front to think of things this way, but once you’ve got a bit of complexity in your data model, you’ll find that falling back on RESTful thinking can help untangle things for you.


URLs

You may think you know what’s in a URL, but which part is the host? protocol (aka scheme)? parameters? path?

Quick Quiz:The URL is: https://www.google.com/search?q=what+is+a+url

  1. What is the “Path”?
  2. What is the “Parameter” portion?
  3. What is the “Top Level Domain”?
  4. What is the “Protocol”?

Once you understand what these components are, you can easily use Ruby’s libraries to help you build your own and send a requests. You also run into specific pieces like the “path” and “parameters” again and again when using Rails.

Answers: 1. /search 2. q=what+is+a+url 3. com 4. https


MVC

You’ve heard about it again and again, but do you really know what MVC is?

MVC is all about organization and Rails is all about MVC. When you build a new Rails project, you get that giant mass of folders and files created. Though it seems like there are an overwhelming number of files inside your app directory, they are highly organized and specifically meant to separate the Model, View, and Controller.

The point of MVC is that the functions of a web application can be broken down into more or less distinct parts. Each part gets its own Ruby class. That’s great for you the developer because, when you want to tweak a specific part of the code base or fix a bug, you know exactly which file to modify and where it is.


 The Path Through MVC

  1. Once a request from a browser comes into your application, at the most basic level:
  2. The router figures out which controller to send it to (ie. for your blog, the Posts controller).
  3. That controller asks the model (ie. Post model) for data and any other tough questions it has.
  4. Then that controller passes off whatever data it needs to the views (ie. index.html.erb), which are basically just HTML templates that are waiting for those variables.
  5. Once the proper view has been pumped full of the data it needs (like the current user’s name), it gets sent back to the client that made the original request.

APIs

When your computer or a server (which you’re programming) wants to make a request to another website, it doesn’t bother clicking on things in the browser, it asks that other website for data directly by using that website’s API. An API is just an interface. (Our web browser goes in the front door to display a bunch of info from facebook, and our web server goes in the side door for the same data (much faster and more direct) via the API.)

So you want to get data from Google Maps to display on your webpage? You hit its API using the rules specified in its API documentation. Just about every big website makes some portion of its data available via an API and you can too quite easily using Rails.

Not all APIs are web-based. Plenty of them use the same HTTP format but are really just designed to pass data between services. In fact, that’s how the components of Rails are all strung together – they use HTTP to communicate with each other.

You’ll actually get a chance to build your own API a little later on, and Rails makes it really easy for you. There’s nothing magical about it – you just tell your controller that you want to respond to requests made by other servers instead of (or in addition to) normal web requests and then specify what exactly you’d like returned (since it probably won’t be an HTML view).


Cookies

Cookies are basically a way for websites to remember who you are from one request to another. Remember – every HTTP request is totally independent of each other one. Meaning that when you go to the Home page of a website and then click on a link to their About page, the web server treats you as a completely new user.

…Unless they’ve given you some cookies (which they almost certainly have). Cookies are little bits of data that your browser sends to the website every time you make a request to it. From the perspective of the web server, it lets the server identify you as the same person who made any of a series of previous requests. It preserves the state of your session.

Go to a website you normally frequent, open up your developer tools, and find the cookies. In Chrome, it’s by clicking on “Resources” then “cookies”. You’ll see them as name-value pairs. Often there will be something like a “user_session” or “token” variable that is some unintelligible string of characters.

Sessions

Cookies are important because they enable you to have a single continuous “session” while you’re interacting with a website. It means you only have to log in once instead of for every single request (which you probably experienced from a broken website at some point in the late 90’s).

Your browser includes all the cookies that a particular website has set along with its normal request and the server uses those strings to figure out which user you are and whether you are logged in, what your settings are (like if you’ve set up viewing preferences) and things like that. It’s also why, when you clear cookies from your browser history, everything seems to get wiped out and go back to the default.

It’s also how some ads seem to follow you from one website to another – another name for them is “tracking cookies”.


 Authentication

On the server side, you’ll interact with cookies and session variables quite a bit. As mentioned above, one of the main uses of these is to determine who the user is, or “authentication”. You’ll basically retrieve the cookie that the user sends you, use it to find that user in your database, and (if the user exists) then you can display the customized web page for that user.

It’s pretty straightforward in theory, but some of the security implications get a bit tricky so luckily the nice folks at Platformatec (http://plataformatec.com.br/) created a very handy gem called “Devise” (https://github.com/plataformatec/devise) which takes care of all this for you. You will be using Devise later.


 Authorization

Authorization is the partner concept to Authentication. Authentication lets you determine WHO the user is, but the idea behind authorization is that you might limit what the person can see based on their permission level. The most common case of this is actually the distinction between a random not-logged-in user and one who is logged in. Another common case of this is the difference between regular users of a website and the admin users who have special privileges.

On the server side, you will end up writing (or using) methods which restrict access to certain types of actions based on who the current user is (or whether the requester is logged in at all). Again, Devise will help you with this by providing some of these helper methods (like for checking whether any user is logged in or who the current user is) for you.


Conclusion

It’s good to understand in the context of what we talked about before about how requests are made because it brings a couple extra layers onto these formerly-independent HTTP requests. Authentication systems allow you to establish sessions which preserve the user’s state (like logged in status) across requests and helps you determine whether the user is authorized to do a particular thing.


Additional Resources

Published on 26 Feb 2013
David Malan teaching CS75 lecture 0, HTTP.

Step 3: Deployment

Introduction

You’ve had a good overview of how your browser will be interacting with your web application but how do you actually get your application onto the web? Up until now, you’ve built everything in the local environment, perhaps accessing the application server in your browser via http://localhost:3000 or something similar. That’s not nearly as rewarding as seeing the application live on the Internet, so we will now cover that final push to deploy your apps to Heroku. Deployment can sometimes be a frustrating process because the errors can be a pain to diagnose and fix, but there are a lot of Stack Overflow posts out there which will help you find your way if you get stuck.

We won’t be digging into the advanced issues of deployment in this lesson. That’s well outside the scope of this course. The point here is to familiarize you with the basic deployment process and help you get your apps online in the first place.  You’ll likely read through this now, get a sense for what’s coming in the future, and then refer back to it when it’s time to actually deploy some of your apps later on.


Heroku Overview

It should be noted that Heroku is far from the only place to deploy, it just happens to be the most straightforward for a beginner. You could also deploy directly to EC2.

Heroku is great for beginners because it’s a free and “simple” push-to-deploy system. Their system is actually built on EC2 but it saves you a lot of hassle. Because of this, when you DO get to the paid tiers, it will be more expensive than EC2 but should be worth it for a while. The best part is that you get free high quality hosting for any number of new apps.


 Instances and Traffic

Heroku works by giving you virtual “Dynos” which run your app. Basically, one dyno means one instance of your application running at one time. That’s sort of like having a single computer run your app, like you do on Localhost. Multiple dynos is like having several copies of your app running simultaneously, which allows you to handle more traffic. The cool thing about Rails is that you can always fire up more instances of your application if you start getting too much traffic and users start having to wait for their requests to be filled.

For most of your apps, one dyno is plenty enough. You can support a lot of traffic using just a single dyno, and Heroku gives you your first one for free. Unfortunately, if you don’t visit your app for a while, Heroku will “shut down” the dyno and basically stop running your app continuously. They don’t want to waste resources supporting the thousands of apps that no one visits.

This means that, the first time someone visits your site in a while, it will take 30-40 seconds to “fire up” a dyno with your app on it. There are a couple solutions to this. You can pay for an additional dyno, in which case Heroku will never idle any of your dynos, or you can set up another service to periodically ping your application (ie. NewRelic, see below).

Heroku lets you do your application management either from the command line (using the “HerokuToolbelt” set of commands) or by going to their website and clicking around. Pretty much all the functions are available in both places, which is handy.


Domains and Naming

Heroku will give you a random application name when you first deploy, something zen like “afternoon-falls-4209”. If you want to visit the app, you can either type $ heroku open on the command line or just go directly to http://afternoon-falls-4209.herokuapp.com. You can change that name to whatever you want, ie. “my-cool-app”, which becomes http://my-cool-app.herokuapp.com.

Note: If you change your app’s name on Heroku, you’ll probably need to manually update your Git remote so Git knows where to send your local application when you deploy to Heroku.

That domain name will always be yours on Heroku. Obviously, in the real world, you want to link it to a custom domain of your own, ie. http://my_cool_domain.com. First you’ll obviously need to purchase the domain from a registrar.  Visit Domainr (https://domainr.com/) to find new domains.

Once you have your own domain, you will need to go in and point it to your herokuapp.com subdomain by changing the appropriate entry in your CNAME file. Where does mail.yourapp.com or www.yourapp.com or calendar.yourapp.com go? That file, which lives at your Registrar, basically defines where incoming requests should go. These settings are relatively easy to change but take several hours to take effect.

You’ll also need to tell Heroku that you’d like to point your app to a custom domain. See Heroku’s Custom Domain Names for Apps Help File (https://devcenter.heroku.com/articles/custom-domains)


Addons

Another great feature of Heroku is add-ons. These are third party applications which have been designed to seamlessly add onto your own. You can view the ones you have via the command line using $ heroku addons or add a new one using something like $ heroku addons:add newrelic:standard. You can also work from the web interface.

Some of the most useful Add-ons are:

1. New Relic APM (https://devcenter.heroku.com/articles/newrelic).  It is an application monitoring and analytics service, so you know when your application has gone down or where your bottlenecks are. They have a free plan which is useful just for the analytics but also has the added bonus of allowing you to set up “pinging” for your application (which prevents it shutting down).See

2. Heroku PGBackups (https://devcenter.heroku.com/articles/heroku-postgres-backups).  This add-on lets you make backups of your database. There’s nothing worse than losing data, and so this app will make your life a lot easier. The free tier lets you manually download backups or set up Rake tasks to do the same.

3. SendGrid (https://devcenter.heroku.com/articles/sendgrid) is an email service, which we’ll cover more later. You can’t send email without help and it’s actually incredibly complex behind the scenes. This add-on makes your life a lot easier by doing most of it for you.

Note that you’ll probably be prompted for your billing information when installing Add-ons (or possibly before) because they need to be able to charge for overages.


Deploying to Heroku

If you haven’t deployed to Heroku before and this is your first time, feel free to just skim this section. It’s meant to be a handy reference for later.

The details of deployment will be left to MichaelHartl in the project – Ruby on Rails Tutorial (https://www.railstutorial.org/book), but we’ll do a quick overview of how it will work. It’s not meant to be a step-by-step guide… for that, please check out Heroku’s Getting Started with Rails 4.x on Heroku (https://devcenter.heroku.com/articles/getting-started-with-rails4).  A typical convention with Heroku commands is that they’re prefixed with either $ heroku run or just $heroku, so running a database migration on Heroku is $ heroku run rake db:migrate and using the console is $ heroku run console.

  • Download and install the Heroku Toolbelt. You’ll likely need to set up the proper SSL configuration so your computer is able to securely move files to and from Heroku.
  • Install Heroku’s special gems. In Rails 4, there were some changes that broke Heroku so they made a really simple gem that you’ll need to add to your application
  • Install the correct database gem.  If you’ve been using SQLite3 as your development database, you’ll need to set up PostgreSQL for production since it’s the only database Heroku uses. This will mean adding the pg gem to your gemfile and putting the correct fields into your database.yml file.
  • Create a new Heroku application from the command line using $ heroku create. This will also add a new remote to your Git setup so that Git knows where to push your app (so you don’t need to worry about that).
  • Push using the command $ git push heroku master.
  • The last step you’ll need to do is manually set up your database. Any time you run migrations or otherwise alter your database, you will need to remember to also run them on Heroku. If it’s your first database, you’ll likely do something like $ heroku run rake db:migrate. If you’ve set up seeds, you can also run them now.

What’s Going On?

When you created the new Heroku app, you also automatically set up the “heroku” remote to point to your application on Heroku. When you execute $ git push heroku master, Git will just ship your code up to Heroku.

From there, Heroku more or less does what you do for your own localhost. First it will take the “slug” of code and files that you uploaded, identify your Ruby version, and run a $ bundle install. It sets up your database connection and then runs the asset pipeline.

We’ll cover the Asset Pipeline later and don’t worry about this if you aren’t familiar with it yet. In development, Rails only partially executes the asset pipeline. It runs all the preprocessors but serves asset files like stylesheets and JavaScripts individually (check your local server logs to see it serving dozens of individual files). In production, Heroku will finish the job by not only running the preprocessors but also mashing your assets into those single files with the timestamp names.

So it doesn’t have to run this part of the asset pipeline (which won’t actually change at all from one visit to the next) every single time a new HTTP request is served, Heroku will “precompile” the assets up front and serve them from the cache.

Once precompilation is complete, Heroku will fire up a dyno with your application on it and you should be able to visit it within 30 seconds or so by running $ heroku open or just navigating directly to the application’s address.


 Essential Heroku Commands

A brief list of Heroku commands you should know:

  • $ heroku run rake db:migrate
  • $ heroku run console gives you a Rails console.
  • $ heroku logs -t shows you your server logs (like you’re used to when running $ rails server) on a streaming basis (which is the result of the -t, or “tail” flag).

See Logging (https://devcenter.heroku.com/articles/logging)

  • $ heroku restart — if your application has failed and won’t start up.

See How to restart a rails server on Heroku? (https://stackoverflow.com/questions/14612695/how-to-restart-a-rails-server-on-heroku)


 Learning to Love Heroku: Errors

You will have errors. The two main places where errors pop up are during the deployment process and when you try to actually run your app (ie. by getting a 500 server error). The key is, as usual, not to panic and to follow a calm, step-by-step debugging process. Especially when you’re first starting out, it’s probably a simple problem so if you check the logs or error output you can usually figure it out directly or Google the message to find a helpful Stack Overflow post.

If you’re several deployments deep and something broke, backtrack to the last working deploy and figure out what you changed before running around in circles and changing config files based on Internet advice. Sometimes it’s unavoidable, but not knowing why something broke can come back to bite you later.


 On Deployment

Your very first few times, you’ll probably run into relatively straightforward errors. Some may have to do with setting up Heroku properly, which should be obvious if the error messages are something to the effect of “we can’t actually find this command that you typed” or “you’re not authorized to do this”.

Another common early mistake is forgetting to include a gem (or forgetting to put it in the correct section of your gemfile. Remember we’re in the production section, not the development section).

Once the early errors are bypassed, another really common class of errors is related to the asset pipeline. For some reason, some gems and configurations seem to mess with Heroku’s ability to precompile assets. You may encounter an asset error when the deployment fails or if your application seems to be unable to locate stylesheets or images (this should be apparent if you’ve got errors in your browser’s console).

Deployment errors, including those with asset precompilation, are often solved by modifying your Rails configuration files. The two main files you’ll probably find yourself needing to edit are config/environments/production.rb (most common) and config/initializers/some_gem.rb (if a gem needs to be configured). Often the articles you read on Stack Overflow will tell you to add or edit one of the options, ie. config.assets.compile = false.

For fixing a precompilation issue, you may also be prompted to manually precompile the assets yourself and then just pass Heroku the resulting file. Sometimes this works. It’s not a magic bullet and it gets to be a pain when you need to re-run the compilation command yourself every time you deploy changes to assets.


 500’s While Running the Application

No one likes getting that bland “We’re sorry but something went wrong” message form Heroku. They serve up a 500 error regardless of which error your application threw, which makes it doubly frustrating to diagnose them. You’ll want to open up the Heroku logs ($ heroku logs -t) to check out the server output.

If this is your first deployment and your very first page served up a 500, did you remember to migrate your database? That’s a common one.

Other 500 errors will just have to be tracked down using the logs. It should incentivize you to build useful error messages into your application logs!

Another common class of errors is related to switching from an SQLite3 database in development to the PostgreSQL one in production (another reason you should wean yourself off SQLite3 and use PG in development as soon as possible). There are just some little things, especially if you’re using direct SQL code or true/false in your ActiveRecord queries (in PG it’s t/f). Postgres errors can be annoying to diagnose so it’s usually best to get them over with in development (when you can operate much faster) than to combine them with any errors you may have in deployment.

Remember Environment Variables (aka “Config vars”)? If you’ve got any gems or add-ons which require special tokens or API codes that you shouldn’t hardcode into your application, you will need to tell Heroku what those variables are. This is another tricky one to diagnose because often times these gems will fail silently and you’ll be left wondering why they didn’t work. We’ll get into this a bit more in the lesson on working with APIs.

To get your environment variables to Heroku, you can either manage them using a gem like figaro (See https://github.com/laserlemon/figaro)  or directly upload them with a command like $ heroku config:set YOUR_VARIABLE=some_value. This will make that variable available to all instances of your application running on Heroku (you won’t need to reset it each time either).

See Configuration and Config Vars (https://devcenter.heroku.com/articles/config-vars)


 Localhost Tricks and Tips

Dialing things back to the local environment, here are a few useful things to know to help you work more efficiently in development:

  • Use $ rails server -p 3001 to create a Rails server on a different port (in the example, port 3001). This way you can run multiple Rails apps at the same time. Just go to http://localhost:3001 now to access the new app.

 Your Tasks

We won’t have too much reading here because many of the links are interspersed with the sections above and, if you’re a complete beginner, you can safely skip this until later. The important thing is to understand conceptually how the deployment process works and have the confidence to locate the documents you need to diagnose issues. The project will have you actually do it.

1. Read Getting Started with Rails 4.x on Heroku (https://devcenter.heroku.com/articles/getting-started-with-rails4) for a step-by-step guide to deploying.

2. Read How Heroku Works (https://devcenter.heroku.com/articles/how-heroku-works) for a better understanding of the tool you’re using.


Conclusion

Deployment is one of the most satisfying parts of building an application -once you get it actually working! You just need to accept that you’ll probably run into various errors during the process and you’re not the first person to do so.

Best of all, once you can deploy an app to the Internet, you’re officially free to go into the world and build applications of your own.


 Additional Resources


Project: Let’s Get Building

Project: Web Refresher

Warmup: RestClient

This is really a warmup. You’ll get a chance to poke around HTTP requests from the command line (IRB actually) and also to play around with a new gem called rest-client. This is a useful (and powerful) gem which helps you make HTTP requests. You can use it to do the basic stuff we’re doing here or much more complicated authentication requests.

You may find yourself using Rest Client later if you need to communicate with another web service that doesn’t have an API library already written out for you (which is pretty rare these days). Or if you get the inclination to test your own API from the command line later.


Your Task

  1. Make sure that you’ve got Rest Client installed ($ gem install rest-client).
  2. Use IRB ($ irb)
  3. require 'rest-client'
  4. Now you’re able to play with the gem. Read its documentation over in the Github repo (https://github.com/rest-client/rest-client)
  5. Use RestClient to do a Google search and examine the results. (You can find the parameters that Google wants in the URL by simply making a search in a normal browser. Pay attention to the q= parameter).

The point is to get familiar with making HTTP requests using your command line, which should prepare you for making them from within a Rails app later.


Project: Ruby on Rails Tutorial

In this project, you’ll dive right into the tutorial by building the site’s static pages. In the second chapter, you’ll get a refresher of the Ruby concepts which will be useful to you along the way. Even if you’re good with Ruby , this is a good chapter to look over to see how some of those concepts are applied to Rails.

Note: Testing

One aspect of the Ruby on Rails tutorial which we haven’t covered deeply is testing.

Michael Hartl does a pretty good job of explaining what’s going on during the Rails Tutorial and the syntax of RSpec is relatively straightforward. If you’ve been following this content up until now, you should find testing in Rails to be a natural transition from plain Ruby tests (and actually a bit more interesting because you get to play with webpages).

If you don’t feel comfortable with testing Ruby yet, it can feel like you’re learning two languages at once. Don’t be discouraged. It takes some getting used to. Luckily RSpec only uses about a dozen different methods again and again and again, the trick is just knowing which order to put them in.

The tutorial covers more specifically the practice of “Test Driven Development“, where you actually write the tests FIRST and THEN write the code to make them pass. That’s helpful for many reasons, not least of which is that you get to make sure your test actually fails if the code doesn’t work. It also keeps you honest by making you only write just enough code to make your tests pass (so your code base stays lean and clean). It can take some getting used to but is a software development practice that is becoming more and more common these days.


A Simple Test Example

This is an example (listing 3.14) from the tutorial:

    # spec/requests/static_pages_spec.rb
    require 'spec_helper'

    describe "Static pages" do

      describe "Home page" do

        it "should have the content 'Sample App'" do
          visit '/static_pages/home'
          expect(page).to have_content('Sample App')
        end
      end

      describe "Help page" do

        it "should have the content 'Help'" do
          visit '/static_pages/help'
          expect(page).to have_content('Help')
        end
      end

      describe "About page" do

        it "should have the content 'About Us'" do
          visit '/static_pages/about'
          expect(page).to have_content('About Us')
        end
      end
    end

If you read through it, even if you’ve never seen code before, you should have a gist of what’s going on. This is an “integration” or “feature” spec (“spec” == “specification” == “test”), which means it deals with making sure your higher level user flows (as the user moves from one page to the next) behave as expected. You’ll also get to do “unit tests“, which are meant to specifically test narrow pieces of functionality like model methods. Both are important.

First of all, this file is just Ruby code (see the .rb). It uses some new methods that are available because you’ve included the rspec gem in your gemfile, but it’s still written in good old Ruby. The require 'spec_helper' in the first line is what gives this spec file (spec/requests/static_pages_spec.rb) all the methods and setup it needs to be run by RSpec properly when you run your test suite (ie. by typing $ rake or $ rspec spec/ on the command line).

When you run the spec file, RSpec stores each #it block as a separate test and then runs them in a random order (which is important to make sure you haven’t accidentally caused one test to influence another). So all the stuff inside the #it block is what’s actually passing or failing if you run the test.

The #describe blocks just help break up the specs and put related ones together. Note that #describe is the same as the #context method you may see at some point.

This ‘bucketing’ of tests is important because you’ll often need to go through some order of things before doing a specific test, ie. “go to the home page”, “click login”, “fill out login form”, “click submit”. By nesting the specs inside describe or context blocks, you avoid having to repeat all those instructions for each individual spec.

You don’t see it here, but you’ll also work with the #before method. This lets you perform some logic before actually running the test, like setting variables (with the #let method) or creating model objects.

It’s also important to note that each test is completely independent of every other test. Your test database gets completely reset each time it moves on to running another test, then RSpec starts from the top and runs the next test. You should be able to see why that is important. A test wouldn’t be very useful if it got polluted by what your other tests were doing.

Now you can see why you nest tests inside the #describe methods and use #before methods to set preconditions. RSpec will rerun that pre-code for every single spec that’s nested below it. If you create an object, ie. a new User, inside the #it block of one of your tests, it won’t exist by the time the next test is run.

Back to the tests above, the first test (inside the block for the #it method) has just two lines. The first, visit '/static_pages/home', is just a necessary step to get you into position to run the test. Because this is an extremely simple spec file, that is inside the #it block. If you ended up running multiple specs that relied on visiting that same page first, you’d see that line abstracted out into a #before block, which would be run before each test.

The second line (expect(page).to have_content('Help'), or with all parentheses expect(page).to(have_content('Help'))) is where the action happens. expect(page) is going to take the current page that we’re “on” and wait for some sort of definitive answer about whether the page passes or fails. .to(have_content('Help')) takes that page (note that it’s chained onto the #expect method) and searches (because of the #have_content method) for an HTML tag that has the word “Help”. If it can’t find it, it will let RSpec know the test should fail. You don’t actually need to know all the specifics of what’s going on behind the scenes for a while, just how to apply them.


Your Task

1. Review Treehouse’s An Introduction To RSpec (http://blog.teamtreehouse.com/an-introduction-to-rspec)

2. Complete Chapter 3 Ruby on Rails Tutorial (https://www.railstutorial.org/book) to get started building the application.

3. Complete Chapter 4 Ruby on Rails Tutorial (https://www.railstutorial.org/book) to see how Ruby will be used in Rails.

4. Look back at this page’s Deployment section.


Additional Resources

Published on 14 August 2012

  • Watch the YouTube video Rails Conf 2013 BDD and Acceptance Testing with RSpec & Capybara (https://www.youtube.com/watch?v=BG_DDUD4M9E). This video gives you a nice angle on BDD and TDD in Rails that you won’t get from the primary sources.

Published on 21 May 2013