1. Ruby on Rails and your First Application In this chapter we will be going over a little bit of the history of Rails, it’s benefit to you and some of the Rails basics. Ruby on Rails is a web framework that had it’s humble beginning in the year 2004. In an upcoming chapter we will get into building your example SaaS app, a Agile/Scrum Daily Standup Tracker. Of course, you will be able to deviate from the example app at anytime with your own business idea, and the concepts will be presented in a way that will transcend through any business logic or differentiations you may have. 1.1 Rails Overview 1.1.1 Rails Rail’s was developed by David Heinemeier Hansson to be a simple *Convention of Configuration Framework*. What that means is in the early 2000s many web frameworks, especially those with Java roots, would have extensive systems of configuration files to get your web applications up and running. David, finding this needless, designed Rails to have deep rooted conventions. Making setting up and changing Rails apps a breeze. Ruby on Rails is open source, meaning it is free to end users and is maintained by contributors from around the world. Rails is powered by the Ruby programming language which is considered by some as one of the most pleasurable languages to program in with its readable expressive nature and it’s modularity. Most times you’ll be finding yourself wondering how it can be so easy to add another resource from database, through RESTful routes and templated views. While new feature additions to Rails have slowed down in recent years, lending to it’s now stable nature, the Rails teams is still keeping pace with other web frameworks and languages in areas such as WebSockets and javascript package management. With its longevity and tremendous community you will be hard pressed not to find an answer or support channel when you are stuck. With a huge database of Question and Answers in Stack Overflow, issue tracking in the Rails Github repositories, over ten years worth of blog posts and tutorials on copious blogging platforms or plenty of books! Most times you can simply Google the problem or exception message and be on your way to solving your issue within seconds. 1.1.2 Gems Gems are Ruby’s self contained packages of code to solve or collapse logical programmatic problems. For instance, there is a gem called Devise that will help create a near end-to-end authentication system. Another gem, Puma, will provide you a threaded http server to server you web application both locally as you develop and on a server in a production environment. There are thousands upon thousands of gems out there to help with most problems you encounter and have been vetted and used by millions in the open source community. 1.2 A Sample App to Get You Started 1.2.1 Rails Gem By default not all systems have Rails installed and most times if a system does have a system level version of Ruby it is older than you would like for current development. So let's go over how you can install a recent version of Ruby, manage multiple versions of Rails, and group gems to have a cleaner separation of gem versions per project. The instructions for this tutorial will address development on OSX, and should work on almost any Unix based system(OSX, Linux, etc). I will defer to a Rails 5 install blog post by another development blog for Windows (http://blog.teamtreehouse.com/installing-rails-5-windows) There are multiple different tools you can use to manage ruby versions such as RVM, RBenv, or Chruby. I am personally still a fan of RVM after all these years, find it easy for beginners to grok and simple to maneuver once you get the hang of it. I recommend visiting the RMV website (https://rvm.io/) for the two simple bash commands you can run to install RVM. I opted not to print the commands in here as one is a digital security measure and may change as time goes on. Once installed, we can begin installing the latest version of Ruby $ rvm list known This will list the current versions of Ruby available to install, there are a lot in the list, but we would focus on the main interpreter MRI and the latest version(2.4.x as of writing). Now the command to install: $ rvm install 2.4.0 Now sit back or maybe go grab a coffee as the install can take anywhere from 1 to many minutes to complete based on Ruby package availability, system speed and plenty of other factors. Once installed you can setup a gemset. A gemset is a way to group installed gems into a specific RVM based folder to keep different projects and their different versions of gems from interfering from each other. Although, with Bundler, this isn’t a huge issue, it doesn’t hurt to take the extra step and keep your gems tidy. Additionally, this command will instruct RVM to use the newly installed version of Ruby at the same time: $ rvm use 2.4.0@sample_app --create The extra --create flag tells RVM to create the gemset if it doesn’t exist(which it doesn’t). Now that we finally have our Ruby and Gemsets in order we can install Rails and start a new sample project to show you the basics of a new Rails app. As we will run this command again, later, specifically for the SaaS app. Please refer to the RVM documentation if you want to dig deeper into any other features of RVM past the basics in this chapter. 1.2.2 Installing Rails and Starting a New App Now that we have Ruby installed, and the gemset ready to go from the previous chapter we can now install Rails. We will install version 5.0.1 specifically as it is the latest, current version and to keep results consistent throughout the book. Now it may not be all smooth sailing when installing Ruby or specific Ruby gems. Just for instance, when trying to install rails on ruby 2.4 on my system from a clean slate, for the purpose of this chapter I ran into an issue with openSSL and libraries needed for a gem called nokogiri(which is used for HTML parsing in rails). Googling the error + the operating system + operating system version will usually have an answer for you within a couple results, and most times the first StackOverflow link you find. Anyway, on with the install $ gem install rails -v 5.0.1 ..and then assuming your install finishes without an error, or after you solve all install issues you can run the following command to install rails. $ rails new sample_app After the command completes your rails app will be installed, rails’ default gem’s installed and default commands and file watchers installed. Also, to note, the `rails new` command has many additional flags and options which you can read through by typing... $ rails new help 1.2.3 Directory Structure Rails comes with a default directory structure that is used to auto-load many particular files and folders. This may seem magical, but it is really Rails’ strong convention over configuration at work. This makes it easy to get started with a base application. In fact, after going over the directory structure, you will fire up the Rails application, and even make a small modification to get your own “Hello World” response! Anyway, onwards and upwards. Let’s go over the directories! Directory Usage app/ This is the main parent folder of your application. All the specific Rails files go in here app/assets In here you can place your app specific javascript, stylesheets and images app/channels New in Rails 5 is ActiveCable. The channels folder will house your ruby files to handle websocket channel negotiations app/controllers Rails controller files, these are generally responsible for handling the routed http request app/helpers Files that provide helper methods to controllers and more often view files app/jobs This folder holds the ruby files of your background jobs app/mailers This folder will hold mailer setup files app/models This folder contains the model files which by default extend ActiveRecord(Rails database ORM) to provide Ruby object instances representing database tables and rows app/views This is where your templates and markup will live Directory Usage bin/ This is where some rails command files exist config/ This will house configuration files and others that may initialize functionality on application startup. db/ Database and database related files lib/ Library modules, aka, one of module syou may right that don’t fit in another specific Rails convention but are not complex enough to be extracted into a gem. log/ Rails creates log files to go over requests, parameters, generated SQL and more public/ Here you can put static files that will often be handled by the server’s webserver(i.e. NGINX) test/ All your test folders and files tmp/ Rails uses this folder to generate temporary files to run and you will rarely if and probably never need to manually touch this folder vendor/ Here you can put third party javascript or stylesheets which you may want Rails to use in its asset pipeline 1.2.4 Rails Server As stated before, you can actually start a brand new project’s application, right away with no additional coding needed. This is actually provided in numerous frameworks as a way to show you, yes, your install worked! As a note, staying with an assumption of OSX in this book, you will use the Unix based “cd” command to change directories. This should work in numerous other shells on Windows and pretty much all Linux systems. $ cd sample_app $ rails server That will move you into the applications directory and fire up Rails’ development server on port 3000. Go ahead and go to http://localhost:3000 and you should see a welcome page Let’s not stop there though! What is any programming book without a “Hello World” example? We will be modify two files to make this work. I will paste in the entirity of these two files and you can use your text editor of choice(Sublime Text, Atom, vim, etc). app/controllers/application_controller.rb class ApplicationController < ActionController::Base protect_from_forgery with: :exception def awesome_action render html: "<h1>Hello, world!</h1>".html_safe end end The addition to the file is the method ‘awesome_action’. Essentially, when a request comes into the app, that is directed to the awesome_action in the ApplicationController, it will render an html string that says “Hello, world!”. The extra method at the end ensures we pass the string through the response with escaped HTML, instead of the literal string, thus allowing the browser to display the text as a heading. As a small note, actions are very rarely assigned in the ApplicationController file and is normally used for methods or functionality that will be extended to most other routers. I will explain and show this in future chapters. So, how do we tell the Rails app to direct the request to the root address to our new awesome_action? Well, we edit the routes file, like so: app/config/routes.rb Rails.application.routes.draw do root to: 'application#awesome_action' end The routes file is responsible for directing incoming https requests based on path, content type and/or http method type to the responsible controller and action. Further along in the book, you’ll see even more Rails conventions to make this quick and painless for the usual REST routes and actions. The router typically uses the ‘controller_name#action’ in multiple methods and parameters and setting the root route is no different. Here we are saying, set the root path to the ApplicationController and the awesome_action action. Which will then use the previously explained controller code to tell the browser to render our HTML message! If you head to http://localhost:3000 again, you will see our new message to the world!