A Rails 4.0 example application to accompany the book Learn Ruby on Rails.
The book introduces basic concepts of Rails development by showing the reader how to build an application that can be used for a typical small business website. The application includes a home page, “about” page, contact form, and option to sign up for a mailing list.
You can build this application in only a few minutes using the Rails Composer tool.
This example application is fully documented in the book Learn Ruby on Rails.
With the book, a complete beginner can create this application without any additional knowledge. The book explains all the code, introducing basic concepts of Rails application development and professional practices.
The example application is more than a learning exercise. The tutorial shows how to build a basic website, using practices recommended by experienced Rails developers. You’ll build a real-world Rails application that can be used by a typical small business. With knowledge of Rails, the website can be adapted and customized to your needs. Features include:
- Home page
- Navigation bar
- “About” page
- Contact page with “contact request” form
- Google spreadsheet datastore
- Mailing list sign-up form
The application uses the high_voltage gem for the “About” page. Additional pages can easily be added. The high_voltage gem makes it easy to add pages with static content (text that doesn’t change) incorporating elements of a site-wide application layout such as header, navigation links, and footer.
For example, using the high_voltage gem, you could add pages for:
- FAQ
- News
- Legal disclaimers
The application home page contains a form that encourages a visitor to enter an email address to sign up for a mailing list. It can be used to collect email addresses for a newsletter or announcement mailings. The tutorial shows how to set up a MailChimp account and use the MailChimp API to add email addresses to a MailChimp list.
The Contact page includes a “contact request” form. The contact form can be adapted for other purposes, such as an appointment request, or customized as a survey form.
When the visitor submits the form, data is saved to a spreadsheet on Google Drive that the site owner can access for review and analysis. An email message goes to the site owner containing the contents of the form.
Google Drive (formerly known as Google Docs) provides an easy way to store and access form data using a spreadsheet. Because Google Drive manages access to the spreadsheet, authentication and authorization are not needed in the application.
The application does not require a database. No pages are generated using information from a database and no user-submitted data is saved to a database. However, the sqlite3 gem must be present in the Gemfile because Rails ActiveRecord is used for form validation.
This is one in a series of Rails example apps and tutorials from the RailsApps Project. See a list of additional Rails examples, tutorials, and starter apps. The other examples are more complex.
To send email from the application, and save data to a spreadsheet on Google Drive, you will need a Gmail account. You can get a free Gmail account if you don’t already have one. Other services, such as Mandrill, can be used to send email from the application. Or you can connect directly to an SMTP mail server to send email. See the article Send Email with Rails for more information.
The application includes a form that allows website visitors to “opt-in” to a mailing list. You’ll need a MailChimp account, which is free. MailChimp allows you to send up to 12,000 emails/month to a list of 2000 or fewer subscribers for free. There is no cost to set up an account. After you have set up a MailChimp account, create a new mailing list where you can collect email addresses of visitors who have asked to subscribe to a newsletter. The MailChimp “Lists” page has a button for “Create List.” The list name and other details are up to you.
With MailChimp, you can send a welcome message automatically when the visitor signs up for the mailing list. It’s a bit difficult to find the MailChimp option to create a welcome message. Strangely, MailChimp considers a welcome message a “form.” Here’s how to find it. On the MailChimp “Lists” page, click the “down arrow” for a menu and click “Signup forms.” Then click “Link to a form.” On the “Create Forms” page, there is a dropdown list of “Forms & Response Emails.” The gray box shows “Signup form.” Click the down arrow. Select the menu item named “Final ‘Welcome’ Email” and you’ll be able to create a welcome message.
We provide instructions to deploy the tutorial application to Heroku which provides Rails application hosting. It costs nothing to set up a Heroku account and deploy as many applications as you want. To deploy an app to Heroku, you must have a Heroku account. Visit Heroku to set up an account.
Before generating your application, you will need:
- The Ruby language – version 2.0.0
- The Rails gem – version 4.0
See the article Installing Rails for instructions about setting up Rails and your development environment.
You have several options for getting the code. You can fork, clone, or generate.
If you’d like to add features (or bug fixes) to improve the example application, you can fork the GitHub repo and make pull requests. Your code contributions are welcome!
If you want to copy and customize the app with changes that are only useful for your own project, you can clone the GitHub repo. You’ll need to search-and-replace the project name throughout the application. You probably should generate the app instead (see below). To clone:
$ git clone git://github.com/RailsApps/learn-rails.git
You’ll need git on your machine. See Rails and Git.
If you want to use the project as a starter application, use the Rails Composer tool to generate a new version of the example app. You’ll be able to give it your own project name when you generate the app. Generating the application gives you additional options.
To build the example application, Rails 4.0 must be installed in your development environment. Run the command:
$ rails new learn-rails -m https://raw.github.com/RailsApps/rails-composer/master/composer.rb
The $
character indicates a shell prompt; don’t include it when you run the command.
This creates a new Rails app named learn-rails
on your computer. You can use a different name if you wish.
You’ll see a prompt:
question Install an example application for Rails 4.0? 1) Build a RailsApps starter application 2) Build a contributed application 3) I want to build my own application
Enter “1” to select Build a RailsApps starter application. You’ll see a prompt:
question Starter apps for Rails 4.0. More to come. 1) learn-rails 2) rails-bootstrap
Choose learn-rails. The Rails Composer tool may give you other options (other applications may have been added since these notes were written).
The application generator template will ask you for additional preferences:
question Web server for development? 1) WEBrick (default) 2) Thin 3) Unicorn 4) Puma question Web server for production? 1) Same as development 2) Thin 3) Unicorn 4) Puma question Template engine? 1) ERB 2) Haml 3) Slim question Continuous testing? 1) None 2) Guard extras Set a robots.txt file to ban spiders? (y/n) extras Use or create a project-specific rvm gemset? (y/n) extras Create a GitHub repository? (y/n)
We recommend Thin in development for speed and less noise in the log files.
If you plan to deploy to Heroku, select Thin as your production webserver. Unicorn is recommended by Heroku but configuration is more complex.
The example application uses the default “ERB” Rails template engine. Optionally, you can use another template engine, such as Haml or Slim. See instructions for Haml and Rails.
You won’t need “continuous testing” if you are a beginner. Select “none.”
Set a robots.txt file to ban spiders if you want to keep your new site out of Google search results.
It is a good idea to use RVM, the Ruby Version Manager, and create a project-specific rvm gemset (not available on Windows). See Installing Rails.
If you choose to create a GitHub repository, the generator will prompt you for a GitHub username and password.
If you get an error “OpenSSL certificate verify failed” or “Gem::RemoteFetcher::FetchError: SSL_connect” see the article OpenSSL errors and Rails.
If you get an error like this:
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed. composer Running 'after bundler' callbacks. The template [...] could not be loaded. Error: You have already activated ..., but your Gemfile requires .... Using bundle exec may solve this.
It’s due to conflicting gem versions. See the article Rails Error: “You have already activated (…)”.
If you’re storing the app in a GitHub repository, please edit the README files to add a description of the app and your contact info. If you don’t change the README, people will think I am the author of your version of the application.
See the article Installing Rails to make sure your development environment is prepared properly.
I recommend using rvm, the Ruby Version Manager, to create a project-specific gemset for the application. If you generate the application with the Rails Composer tool, you can create a project-specific gemset.
Here are the gems used by the application:
- activerecord-tableless – helps to use Rails without a database
- bootstrap-sass – Twitter Bootstrap for CSS and JavaScript
- figaro – configuration framework
- gibbon – access to the MailChimp API
- google_drive – use Google Drive spreadsheets for data storage
- high_voltage – for static pages like “about”
- simple_form – forms made easy
These gems make development easier:
- better_errors – helps when things go wrong
- quiet_assets – suppresses distracting messages in the log
- rails_layout – generates files for an application layout
If you used the Rails Composer tool to generate the example app, the application template script has already run the bundle install
command.
If not, you should run the bundle install
command to install the required gems on your computer:
$ bundle install
You can check which gems are installed on your computer with:
$ gem list
Keep in mind that you have installed these gems locally. When you deploy the app to another server, the same gems (and versions) must be available.
The application uses the figaro gem to set environment variables in the config/application.yml file. The .gitignore file prevents the config/application.yml file from being saved in the git repository so your credentials are kept private. See the article Rails Environment Variables for more information.
Modify the file config/application.yml:
# Add account credentials and API keys here. # See http://railsapps.github.io/rails-environment-variables.html # This file should be listed in .gitignore to keep your settings secret! # Each entry sets a local environment variable and overrides ENV variables in the Unix shell. GMAIL_USERNAME: Your_Username GMAIL_PASSWORD: Your_Password MAILCHIMP_API_KEY: Your_MailChimp_API_Key MAILCHIMP_LIST_ID: Your_List_ID DOMAIN_NAME: example.com OWNER_EMAIL: [email protected]
For the Gmail username and password, enter the credentials you use to log in to Gmail when you check your inbox.
To add an environment variable for the MailChimp API key, Log in to MailChimp to get your API key. Click your name at the top of the navigation menu, then click “Account Settings.” Click “Extras,” then “API keys.”
To find the MailChimp list ID, you must have already created a MailChimp mailing list. On the MailChimp “Lists” page, click the “down arrow” for a menu and click “Settings.” At the bottom of the “List Settings” page, you’ll find the unique ID for the mailing list.
If you already have a custom domain name you’ll use when you deploy the application, you can replace example.com
. If you deploy the application to Heroku, you’ll replace example.com
with the unique name you’ve given your application on Heroku. You’ll have to wait until you deploy to know the name you’ll use on Heroku.
You’ll send email messages to the OWNER_EMAIL
address when a visitor submits a contact request form. Replace [email protected]
with an email address where you receive mail.
All configuration values in the config/application.yml file are available anywhere in the application as environment variables. For example, ENV["GMAIL_USERNAME"]
will return the string “Your_Username”.
If you prefer, you can delete the config/application.yml file and set each value as an environment variable in the Unix shell.
You can check that your application runs properly by entering the command:
$ rails server
To see your application in action, open a browser window and navigate to http://localhost:3000/.
You should see a home page with a placeholder photo and the “sign up” form.
Enter your email address and click the “sign up” button. You should see the page redisplay with an acknowledgment message. Try entering an invalid email address such as “me@foo”, or click the submit button without entering an email address, and you should see an error message. You’ll have to log in to MailChimp and check your mailing list to see if the new email address was added successfully.
You should be able to click the navigation links for “About” or “Contact” and see those pages.
Submitting the form on the “Contact” page should send an email mesage to the site owner’s address and save the data to a spreadsheet on Google Drive. Visit your Google Drive account (“Drive” is in the navigation bar when you visit the Googe Search or Gmail home pages). You’ll see a list of Google Drive files. The newest one will be a Learn-Rails-Example spreadsheet. Open the file and you will see the data from the contact form. Whenever a visitor submits the contact form, the spreadsheet will update within seconds.
Stop the server with Control-C. If you test the app by starting the web server and then leave the server running while you install new gems, you’ll have to restart the server to see any changes. The same is true for changes to configuration files in the config folder. This can be confusing to new Rails developers because you can change files in the app folders without restarting the server. Stop the server each time after testing and you will avoid this issue.
For your convenience, here is a Tutorial for Rails on Heroku. Heroku provides low cost, easily configured Rails application hosting.
You’ll need to precompile assets before you commit to git and push to Heroku:
$ RAILS_ENV=production rake assets:precompile $ git add -A $ git commit -m "assets compiled for Heroku" $ git push origin master
You’ll need to set the configuration values from the config/application.yml file as Heroku environment variables. See the article Rails Environment Variables for more information.
With the figaro gem, just run:
rake figaro:heroku
Alternatively, you can set Heroku environment variables directly with heroku config:add
.
$ heroku config:add GMAIL_USERNAME='[email protected]' GMAIL_PASSWORD='secret' $ heroku config:add MAILCHIMP_API_KEY='mykey' MAILCHIMP_LIST_ID='mylistid' $ heroku config:add OWNER_EMAIL='[email protected]' DOMAIN_NAME='myapp.herokuapp.com'
Complete Heroku deployment with:
$ git push heroku master
See the Tutorial for Rails on Heroku for details.
Problems? Check the issues.
The Learn Rails book provides additional documentation.
Please create a GitHub issue if you identify any problems or have suggestions for improvements.
Your best source for help with problems is Stack Overflow. Your issue may have been encountered and addressed by others.
You can also try Rails Hotline, a free telephone hotline for Rails help staffed by volunteers.
If you make improvements to this application, please share with others.
Send the author a message, create an issue, or fork the project and submit a pull request.
If you add functionality to this application, create an alternative implementation, or build an application that is similar, please contact me and I’ll add a note to the README so that others can find your work.
Daniel Kehoe implemented the application and wrote the tutorial.
Is the app useful to you? Follow the project on Twitter: @rails_apps
and tweet some praise. I’d love to know you were helped out by what I’ve put together.
Copyright ©2013 Daniel Kehoe