⭐ If you would like to buy me a coffee, well thank you very much that is mega kind! : https://www.buymeacoffee.com/honeyvig Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies
Showing posts with label Ruby on Rails. Show all posts
Showing posts with label Ruby on Rails. Show all posts

Thursday, November 10, 2011

Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools

Warning: Freelancing Is Not for Everyone

A freelancer is a self-employed person who pursues a profession without a long-term commitment to any particular employer. Your curiosity in this opportunity was probably sparked by posts marked “Freelance” or “Work from anywhere” on the myriad of job boards around the Web. Freelancing is equal parts freedom and responsibility. While you have the freedom to choose when you work, where you work and what you work on, you are also responsible for everything: deadlines, finding work, the quality of your work, communication and so much more.

Photo by Dmitry Belitsky
Ruby, with all of its frameworks and libraries (such as Rails, Merb and Sinatra), is a practical tool to use in your freelance Web development career because of its focus on clean code, object-oriented syntax, efficient development practices and strong community (whether a simple IRC chat room or large conference). For all of these reasons, I find that it is also quite fun to use and exciting to be a part of.
So, your skill may be in Ruby and your approach is to freelance, but it’s not that easy: freelancing is no walk in the park. It could become a living nightmare if you’re not able to use your time efficiently and remain focused and motivated until a project comes to a close. It could also become a nightmare if you market yourself poorly, are constantly desperate for work or surrender too much power to a client, putting you in the position of a monkey-worker responding to petty demands.
Over the four years that I’ve been freelancing, I have figured out the intricacies of it and grown to completely love it. I cannot envision myself working any other way.
[Editor's note: Have you already got your copy of the Smashing Book #2? The book shares valuable practical insight into design, usability and coding. Have a look at the contents.]

Pros


Photo by Giorgio Montersino.
Be your own boss.
Report to no one but yourself. You are at once king, countryman, peasant, squire, blacksmith and merchant. You will work on excruciatingly boring tasks, grand and exciting ventures and everything in between. You will have very tough times and very beautiful times.
Enjoy your freedom.
You have the freedom to work when and where you please, the freedom to structure your day as you please and the freedom to fail. Structure and discipline can be daunting and intimidating but also rewarding and empowering.
Choose what to work on.
Want to spend 50% of your time on open-source projects? Interested in building your own Web app? You have the power to make that a reality. Want to work exclusively on projects in social media? Make it happen.
Set your rates.
Value is both a reflection of how you perceive yourself and how others perceive you. Are you capable of meeting deadlines, communicating well and delivering quality code? Charge what you think that is worth. Often the market will decide. If you are just starting out, charging $80 per hour will be hard; you have to earn that rate over time and with experience.
But what’s to stop you from charging $80 per hour after just a year of full-time freelance work as a Ruby developer? Only yourself. You will have to be confident, and I suspect that most people reading this article do not charge that rate. But if you truly feel capable, then by all means.
In sum, you will experience highs and lows, but with the right attitude, the lows will always pay off.

Cons


Selling yourself
Many dislike the notion of having to sell themselves. That’s understandable: the task is certainly not without its unpleasantness. If coding is an art, then like any good artist you’ll be critical of your own work. But maintain perspective. Recognize that you have to take responsibility for the quality of your code, but also understand that your clients probably won’t be programmers themselves. Hacking together something that works will be okay in many cases; and if it breaks because it was poorly written, offer to fix it for free.
When you write code that is efficient and powerful, explain as much to the client in vocabulary that they will understand; something like, “I changed the application so that it can perform × task at twice the speed.” Remember that your clients will likely not be developers and that in the freelancing game communication skills are often more important than programming skills. Be aware of yourself, be realistic in your expectations of yourself, be humble yet straightforward, and understand that if you truly believe in yourself, selling becomes easy. You are just being honest when you say to someone, “I’m good at what I do.”
Responsibility and discipline
No one will prevent you from procrastinating. No one will stop you from meeting with a friend in the middle of the day for lunch or a walk. No one will tell you what to do or when to do it. This may sound amazing—and it is if you’re disciplined—but discipline becomes rarer as we get increasingly overloaded with details that demand our attention. (In my opinion, discipline is one of the most important traits any freelancer can have.)
Time management
Manage your time as if each hour were a brick of gold. Time is more precious than any other resource. Tools are out there to help you become aware of how you spend it and that help you figure out where you are going wrong and right. Harvest, Trails, Tick and a slew of other applications are all designed to help you understand how you spend your time.
Emotions
The freelancing life is often isolating and can get lonely. It has often been said that running a small business is an emotional roller coaster: well, it is. Fight the inclination to stay cooped up and out of touch with the world. Get out and meet people; it could save you from serious bouts of depression.
Ultimately, freelancing is not for the faint of heart, but that doesn’t mean it isn’t worth your best shot!

Tools Of The Trade

Plenty of tools will help you get your projects done, but the best ones help you complete your projects effectively. We all work differently, and numerous tools are at our disposal that will help us accomplish the same task in different ways.
You’ll find a lot of discussion on the Web (some of it bordering on holy wars) about the relative merit of Vim vs. Emacs, Prototype vs. jQuery, Haml vs. ERB. But it doesn’t matter what you use: results matter. Properly caring for your code will help you grow, so use tools that allow you to craft the best possible code. Tools are always relative.

Text Editor (Vim, Emacs, TextMate, IDE)

MacVim screenshot
As with most other tools, choose a text editor by trying it out. I used TextMate in the past and now work in Vim most of the time. Some folks prefer Emacs or big IDEs such as RubyMine. You can try all of these just by downloading a trial version. You’ll know when you’ve found your favorite.

*Nix Server Management and Working in the Unix Shell

Many useful resources on Linux server management are available in various Slicehost articles. You’ll also find a lot of info about working in the command line at commandlinefu.com. Beyond that, let Google guide you.

Ruby Will Become Your Best Friend

Ruby
Yukihiro Matsumoto (a.k.a. Matz), creator of Ruby, said that he wanted to minimize his frustration with programming, minimize his effort in programming and have fun with software development. In fact, Ruby was designed to make programmers happy. But while Ruby is simple in appearance, it is complex inside, like the human body.
As hard as it is to believe, Ruby has been around for 15 years. As the years go by, more and more people see the beauty in this language and become passionate users. Today, Ruby is the language of choice for hundreds of thousands of developers worldwide. Several lively Ruby conferences take place each year around the world. And big corporations use Ruby: Microsoft and Sun have created their own Ruby interpreters (IronRuby, jRuby), and Apple now includes Ruby with OS X 10.6. Countless Ruby developers are hired every day on every continent.
The community around a language is one of my primary considerations in deciding whether to learn that language. Ruby’s community is vibrant and growing; it is friendly to people of all skill levels and comprises both online communication such as chatting and mailing lists and in-the-flesh interaction at meet-up groups and conferences. Ruby and its frameworks—especially Rails—have become their own sub-culture; full of life and passion and changing every day.
A very useful resource is confreaks.com, where you can watch videos from great Ruby-related events such as Rubyconf, acts_as_conference and more. Highly recommended.
Popular Ruby-related resources:
  • The official Ruby website
  • Ruby mailing list
    A useful place to get help or advice from those active in the Ruby community.
  • Ruby Inside
    A Ruby blog with daily news, links, code and tips. Claims to be “the #1 Ruby programming blog.”
  • RubyFlow
    A community-driven Ruby links website, with more than 1000 members. Posts are made by members of the community. Enjoy the links and leave comments.
  • RubyForum
    Helpful forum for Ruby and Rails.
  • Ruby Learning
    “A thorough collection of Ruby study notes for those who are new to the Ruby programming language and in search of a solid introduction to Ruby’s concepts and constructs.”
  • Planet Ruby
    RSS aggregator of top Ruby-related blogs.

The Ruby on Rails Framework (and Alternatives: Merb, Sinatra, Ramaze, Rango)

Rails is my MVC framework of choice because of its ease of use as well as the vast community of passionate users who stand behind it. If you’d like to learn it, a great starting point is Agile Web Development With Rails. UC Berkeley has a series of intensive Ruby on Rails classes on YouTube, which are rather useful. And a lot of screencasts are on the Web. I also like confreaks (already mentioned but worth a second push); it delivers videos from large Ruby conferences, and I’ve learned a lot from the talks.
Railsguides
Some general Rails-related resources:
Some more specific tools for Ruby to check out:
  • The Ruby Development Tool
    An IDE consisting of Ruby-aware features and plug-ins for the Eclipse platform.
  • Watir
    An open-source (BSD) library for automating Web browsers. It allows you to write tests that are easy to read and maintain. It is at once flexible and simple.
  • Radrails
    A Ruby on Rails IDE, either standalone or as an Eclipse plug-in. Free, open source and cross-platform, Radrails includes an integrated shell console, rich code completion for Ruby and Rails, an integrated debugger and cloud deployment options. Radrails
  • Heroku
    An online Ruby on Rails cloud platform-as-a-service. A “fast, frictionless and maintenance-free Rails hosting platform” with a free plan. The platform is effective, though not invincible.
  • Capistrano
    An open-source tool for running scripts on multiple servers, most commonly used to deploy Web applications. It automates the process of making a new version of an application available on one or more Web servers, including support for tasks such as changing databases.
  • The Ruby Toolbox
    Provides an overview of tools available to Ruby developers. Tools are sorted by category and rated according to the number of watchers and forks in the corresponding source code repository on GitHub, so you can easily figure out your options and which are the most common ones in the Ruby community. Rubytoolbox
  • RailRoad
    “A class diagrams generator for Ruby on Rails applications. It’s a Ruby script that loads the application classes and analyzes its properties (attributes, methods) and relationships (inheritance, model associations like has_many, etc.).”
  • Instant Rails
    “A one-stop Rails runtime solution containing Ruby, Rails, Apache and MySQL, all preconfigured and ready to run (on Windows, OS X, Linux and BSD). No installer—you simply drop it into the directory of your choice and run it. It does not modify your system environment.”
  • Ruby on Rails Toolbox
    A list of 20+ tools to help you with your Ruby on Rails coding.

TDD and BDD

Test-driven development (TDD) is a software development technique that involves repeating a very short development cycle: the developer writes a failing automated test case that defines a desired improvement or new function; then they produce code to pass that test; and finally they refactor the new code to meet recognized standards.
Behaviour-driven development (BDD) is an evolution of the thinking behind TDD and acceptance test-driven planning. It brings together strands of TDD and domain-driven design in an integrated whole, making the relationship between these two powerful approaches to software development more evident.
Cuke Logo
BDD helps focus development on the delivery of prioritized, verifiable business value by providing a common vocabulary (also referred to as an “ubiquitous language”) that spans the divide between business and technology.
Cuke screenshot

HTML, CSS, HAML, SASS, LESS

Nothing can be done on the Web without hypertext mark-up. Every page has its own mark-up and style, and you have to know the basics in order to work with mark-up. Learning HTML basics should take about an hour, and becoming a CSS expert a lot more time, but everything starts with your first step. Once you know how each works, diving into tools that simplify them, such as HAML, SASS and LESS, will be enjoyable and rewarding.

VCS (Version Control Systems)

Version control is essential whether you work alone or on a team, because it tracks all significant changes you have made to a project (called “commits”), and you can easily save the project’s growth history, make new branches to test new functionality, jump back and forth through changes and distribute those changes to others involved in writing the code. I prefer Git and use it most often. It’s fast and reliable, but other systems offer their own functions and strengths. “7 Version Control Systems Reviewed” covers the spectrum of options.
Git Logo
“Git is a free distributed revision control, or software source-code management, project, with an emphasis on being fast. It was initially designed and developed by Linus Torvalds for Linux kernel development.”
Wikipedia
Here is a list of helpful resources to help you jump into working with Git:

Finding Clients

You’ve weighed the pros and cons, and the pros won. You’ve learned enough Ruby and Rails to start looking for work. Now, where do you find clients?
Finding clients is a big topic, so I’ll stick to the basics for now and leave out details on marketing strategies and brand development.
Communicate with potential clients first through simple emails. Write your thoughts in short and effective paragraphs; be selective with your words, and get to the point quickly, mindful of the time people are spending reading your message. You will not only deliver your message effectively but show that you are focused on important matters and that you avoid wasting people’s time.
If you have no portfolio, you may have to do work for very little pay—or even for free—to entice prospects. As you develop your portfolio, describe each project very briefly (one to two sentences), and then start adding these summaries to your emails. The inclusion of references to real work greatly increases your chances of securing more work.
In your search, follow up on every interesting job posting that you’ve found, mentioning your professional experience, technologies you know and your professional qualities, such as being responsible and being able to deliver projects on time and on budget. Ideally, you would show testimonials from previous clients.

Job Boards

Workingwithrails Job Board Screenshot
A lot of freelance job boards are around. Here are the ones I know of and have used successfully:

Contributing to Open Source

Github
If you want clients, you need to prove yourself. Nothing speaks better of developers than their code (although technical skill is only part of the puzzle).
Choose projects that interest you; you’ll get better results. Choose projects that give you a chance to learn and grow. But be careful: your learning should not prolong project deadlines. I find that the best projects are those in which I can work with a passionate team and learn new things along the way.

Learn How People Hire

Read articles that explain how to hire developers for insights into the hiring and hunting process. Articles such as these:

Get Your First Project

If you have no previous development experience, create some first. Write tests for open-source apps, fix bugs, put together a simple Web app: over time you will have developed a portfolio and eventually become confident enough to take on client work.
One way to start: choose a project on GitHub and learn its internals; offer help by writing tests and fixing bugs. Over time you will learn how to work as a team player and how to read code written by others. This knowledge will help you tremendously.

Focus on Building Your Profile

Linkedin
This could be the first thing people read about you, and first impressions count. Make this impression as good as possible, and use all of the best-known networks: LinkedIn, Working With Rails and GitHub.

Create a Website or Blog

You should have your own website or blog because that’s expected in the Web development field. On it, you can describe your professional experience, new technologies that you have been working with, book reviews (this might also bring in new readers from search engines) and interviews with people you find interesting. Include productivity tips and personal thoughts on things you’re interested in. Remember, describe your own experiences and show your face. Be authentic. Read about writing for the Web on useit.com and A List Apart (the writing section).

Get Involved in the Community

Railsbridge
Make something useful for yourself and people like you. This could be a library or plug-in, an article or a tutorial—anything usable. Writing documentation for RailsBridge will surely increase your understanding of Rails, too.

Write a Lot of Emails to Employers

If all goes well you might have a pool of a few jobs to chose from. Choose wisely, and then work vigorously to deliver something great—on time! When you reach out at first, don’t expect many responses. If you get only a few clients from 50 emails that you send, you’re doing good. Now you need to get things done, and that takes time and a good process.

Working Process

There are many well-known methods of working, and each offers a different approach to solving the same problem: how the heck do I get things done effectively?
Here are the two techniques I follow:
Getting Things Done (GTD) is a method created by David Allen and described in his book of the same name. GTD relies on the principle that a person needs to move tasks out of their brain by recording them externally. That way, the mind is freed from having to remember everything that has to get done and can concentrate on actually performing those tasks. Check out the interesting introductory video by David Allen on YouTube.
GTD is an easy step-by-step and highly efficient method of achieving this relaxed, productive state. It includes:
  1. Capturing anything and everything that has your attention;
  2. Categorizing actionable tasks discretely as outcomes and concrete next steps;
  3. Organizing reminders and information in the most streamlined way, in appropriate categories, based on how and when you need to access them;
  4. Staying current and “on your game” with appropriately frequent reviews of the six horizons of your commitments (purpose, vision, goals, areas of focus, projects and actions).
The Pomodoro Technique is a way to get the most out of your time. Turn time into a valuable ally to accomplish what you want to do, and chart continual improvement in the way you do it. Francesco Cirillo created the Pomodoro Technique in 1992. It is now practiced by professional teams and individuals around the world. A great way to learn it is through this cheat sheet.
It can be described simply in five steps:
  1. Choose a task to be accomplished;
  2. Set the Pomodoro (i.e. the timer) to 25 minutes;
  3. Work on the task until the Pomodoro rings, and then put a check on your sheet of paper;
  4. Take a short break (about five minutes);
  5. After every four Pomodoros, take a longer break.
My own productivity method mixes these two techniques. I break big tasks into smaller chunks, and then I write them down in a Pomodoro-like table and work on them for 25 to 30 minutes, with 5 to 10 minutes breaks.

Getting Perspective

Get Some Rest

Rest
Photo by Dmitry Belitsky
Rest is just as important as work. They are a yin and yang, work and rest. Rest both your body and mind. No one can work much more than 40 hours per week and still be productive.
Here are a few tips to rest the right way:
Take a break.
If you have worked on the computer for more than an hour, switch your focus. Go exercise, wash the dishes or take a walk. Attend to something that doesn’t involve staring incessantly at a screen. When you get back to work, you will find your mind relaxed and rested.
Meditate.
Meditation comes down to us from the ancient sages as a method of training the mind to be at peace. It helps you to relax your mind and body and become at once joyful and calm. There are a lot of different techniques of meditating; try the simplest one, making it a part of your daily routine. This is a great
article on meditation
because it relates to creative fields, but the principles apply to any profession (and who says good code isn’t art, anyway?).
Go for a walk.
Walking is a great way to calm your mind, exercise your body and take in fresh air. Integrate walking into your daily or weekly routine, too.
Don’t overeat.
Overeating takes blood away from your brain and moves it to your hard-working stomach to help it digest all that food. This makes you tired and less focused. Food is great, but don’t overdo it.
Take up a non-computer-related hobby.
We should all find something that keeps us away from our computers for a while. If you live alone and work as a freelancer, you can lose yourself for weeks, working too hard and forgetting everything else. Jamis Buck has some great advice on the subject:
“You should be well balanced. Computers are great and everything, but you should definitely have hobbies that are completely unrelated to computers. In the last two years I’ve taken up both wood carving and string figuring, and they have helped me immensely in recovering from burn-out.”

Success

  • “Everything you write is crap, so always try to improve yourself.”
    Dirkjan Bussink.
  • Hard work is the secret to success.
  • Passion is critical; it makes or breaks any endeavor.
  • Love what you do.
  • “Never let anyone (yourself included) convince you not to do something that will make you happy or fulfilled.”
    Yehuda Katz

Video Resources

Parting Thought

Decide how good you want to be. Do you want to master the craft or just fulfill the basic needs of employment? As a freelance developer, you might find yourself in a constant struggle. You could be forced to produce code that you are dissatisfied with because of a tight deadline or unforeseen problems with other parts of the project. Be patient and relentless. Know that you will become more skilled over time, and trust that you will eventually—even if it takes years—be proud of your abilities.

Tuesday, November 8, 2011

Setup A Ubuntu VPS For Hosting Ruby On Rails Applications

Let’s assume you have built a nice little Ruby on Rails application on your local development machine. Now it’s time for the application to go live. But where should you host this application? You know that you (or your client) do not have much money to spend, and so you look at the options. You notice right away that managed hosting of applications tends to be relatively expensive. Heroku is a good option, but it doesn’t give you storage space, and more importantly, it lacks full control. Luckily, you have a suitable alternative: a VPS.
This tutorial will help you get through the steps required to set up an Ubuntu VPS that is capable of hosting (multiple) Ruby on Rails applications. This tutorial builds on part 1, “Set Up An Ubuntu Local Development Machine For Ruby On Rails.” We recommend that you follow that part first and use the same Ubuntu local development machine that you set up there to walk through this part.
Screenshot

Wait… A VPS?

VPS stands for virtual private server. It is a virtual machine offered by Internet hosting companies. With a VPS, you get your own virtual slice of real estate that lives with other virtual slices on one physical server. This virtual machine is capable of running an operating system, a Web server and database software. A VPS comes with full control (or root access) and, with most hosting companies, at a very reasonable price. And because a VPS is capable of running multiple Ruby on Rails applications, the costs of the VPS can be spread.

Quick Overview

In this tutorial, we’ll log into the VPS, add a new user and configure SSH connections so that the VPS is more secure. Then, we’ll install Ruby and RubyGems using the Ruby Version Manager (RVM) script. In turn, we’ll install Rails and Capistrano using RubyGems. And then we’ll install Passenger and take care of the Nginx Web server installation. The VPS will also feature a PostgreSQL database.
At the time of writing, the latest versions are Ubuntu Server 10.10, Ruby 1.9.2 and Rails 3.0.7. These steps were also tested on Ubuntu Server 10.04 and the upcoming Ubuntu Server 11.04 release.
During this tutorial, we will make extensive use of the Linux command line. A short glossary at the end of this tutorial describes the relevant Linux commands.

Up And Running

First, find a suitable host and purchase your VPS (if you don’t have one already). Make sure the host allows you to install Ubuntu on a VPS; most hosting companies will because it is a popular choice for VPS’. I chose a 512 MB VPS, which should be sufficient to run multiple small Ruby on Rails applications.
For those without a VPS, you can still follow along using virtualization software like VirtualBox. VirtualBox is open-source software and available in the Ubuntu Software Center or via the official website. Make sure when setting up your virtual machine that your network adapter is set to “Bridged” (Right clickSettingsNetworkAttached to: Bridged Adapter). This way, your virtual machine will get its own IP address on your local network. Just install a fresh copy of Ubuntu Server, select “OpenSSH server” during installation, and skip the next two steps. You can log in directly via the VirtualBox window or, if you know the IP address of the server, via SSH.
Log into your VPS host’s control panel, and install a fresh copy of Ubuntu Server. Make sure to submit a safe “root” password, and boot the VPS.

Log Into Your VPS

We’ll log into our VPS using SSH. SSH stands for secure shell and is a network protocol. It enables computers to communicate via an encrypted connection.
I assume you know the IP address of your VPS (if not, look it up in your host’s control panel), and that “root” is the default user, and that you know the “root” password, and that SSH is installed.
While using the domain name of the VPS is technically possible, we will log in using the VPS’ IP address. Setting up the domain name of your VPS is very context-specific and beyond the scope of this tutorial.
Now open up a terminal window on your Ubuntu local development machine, and log into your VPS:
1$ ssh default-user@vps-ip-address
For example:
1$ ssh root@123.456.7.890
You might have to type yes and then provide the “root” password. In about a second, you should be logged in.

Secure Your VPS

For security reasons, you should do as little as possible as “root.” So, we’ll create a new user and assign administrative rights to it. To make use of its administrative rights, the user needs to explicitly invoke the “sudo” command, which adds a security layer to the system administration. First, create a new user:
1$ adduser your-user-name
For example:
1$ adduser johndoe
Provide a safe password (filling in the user details is optional). Now, make the new user a member of the “admin” group, which grants the user administrative rights (by invoking the sudo command).
1$ adduser your-user-name group-name
For example:
1$ adduser johndoe admin
Securing your SSH (server) configuration is the next step. Because every Unix system has a “root” user by default, you should disable “root” from logging in using SSH. This makes your system less vulnerable to brute force attacks.
1$ nano /etc/ssh/sshd_config
Set PermitRootLogin to no, and reload the SSH configuration so that the changes take effect. Although “root” will be disabled from logging in in future, the current “root” user connection will be maintained.
1$ /etc/init.d/ssh reload
Now, log out of your VPS as “root,” and log back in as the new user.
1$ logout
2$ ssh your-user-name@vps-ip-address
For example:
1$ ssh johndoe@123.456.7.890
The system is more secure now that a new user has been created and “root” has been disabled from logging in via SSH. Some of the upcoming steps repeat the steps we took in part 1 of this tutorial, while also getting us up to date and installing RVM, Ruby, RubyGems and Rails.

Get Up To Date

Now, let’s get up to date. The first three commands below will, in turn, update the package lists, upgrade currently installed packages, and install new packages and delete obsolete packages. You’ll end up with a VPS that is fully up to date. The final command will reboot the VPS, which is good practice after updating a lot of packages.
1$ sudo apt-get update
2$ sudo apt-get upgrade
3$ sudo apt-get dist-upgrade
4$ sudo reboot

Prepare Your VPS For RVM

Wait a minute or so for the VPS to reboot. Once it has, log back into the VPS from a terminal window.
1$ ssh your-user-name@vps-ip-address
For example:
1$ ssh johndoe@123.456.7.890
The RVM script needs some packages in order to be installed, namely Curl and Git. Curl is a tool to transfer data using a range of protocols (such as HTTP and FTP). And Git is “a free and open-source, distributed version control system designed to handle everything from small to very large projects with speed and efficiency.” Git is the choice for version control among most Ruby on Rails developers.
1$ sudo apt-get install curl
2$ sudo apt-get install git-core

Install RVM

Now we can install RVM. RVM stands for Ruby Version Manager and is “a command line tool that allows you to easily install, manage and work with multiple Ruby environments, from interpreters to sets of Gems.” The following command takes care of installing the script. RVM will be installed in the home directory of the currently logged-in user:
RVM installation
Navigate to the home directory, and edit the user’s bash profile. This ensures that the RVM script is loaded every time the corresponding user logs in. To edit the bash profile, we use Nano. Nano is a simple command line text editor, and we will use it again in this tutorial.
1$ cd
2$ nano .bashrc
Add the following line to the end of the user’s bash profile.
1[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"
Load the script into the current shell session by reloading the user’s bash profile. This way, the rvm command will be made available.
1$ source .bashrc
You can verify whether the RVM script is working by entering the following command:
1$ type rvm | head -1
If everything is set up correctly, the shell should return that “rvm is a function.” If it doesn’t, please go over to the RVM website and look under “Troubleshooting Your Install” to see how to make it work.

Prepare Your VPS For Ruby And RubyGems

RVM comes with a handy tool for seeing the dependencies needed to compile and install Ruby and RubyGems from source.
1$ rvm notes
Look at the dependencies listed under the regular version of Ruby, and install these. Some packages might already be installed.
1$ sudo apt-get install build-essential bison openssl
2libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev
3libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3
4libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev

Install Ruby And RubyGems Using RVM

On the one hand, we have Ruby. It is “a dynamic, open-source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.”
On the other hand, we have RubyGems. It is “the premier Ruby packaging system. It provides a standard format for distributing Ruby programs and libraries, an easy to use tool for managing the installation of Gem packages, a Gem server utility for serving Gems from any machine where RubyGems is installed, and a standard way of publishing Gem packages.”
Like the RVM command described above, there is also a command to see what versions of Ruby are available to install using RVM. Have a look at the available Ruby versions.
1$ rvm list known
Install a regular version of Ruby. Because Ruby gets compiled from source, this might take a while.
1$ rvm install 1.9.2
Compiling Ruby
Start using the installed Ruby, and set this version as the default.
1$ rvm --default use 1.9.2
Check the Ruby and RubyGems versions to see whether they have been properly installed.
1$ ruby -v
2$ gem -v
If necessary, manually updating RubyGems and the Gems is possible.
1$ gem update --system
2$ gem update

Install Rails Using RubyGems

Rails Gem itself is the only thing left to put on Ruby on Rails. Installing this is one of the easiest parts of this tutorial. It is installed using RubyGems, invoked by the gem command. When the installation finishes, check the Rails version to see whether Rails has been properly installed.
1$ gem install rails
2$ rails -v
Versions

Install Passenger Using RubyGems

Phusion Passenger “makes deployment of Ruby Web applications, such as those built on the revolutionary Ruby on Rails Web framework, a breeze.” It is a module for running Ruby on Rails applications in conjunction with a Web server such as Nginx.
You can install Passenger using RubyGems and then check the Passenger version to see whether Passenger has been properly installed.
1$ gem install passenger
2$ passenger -v

Install Nginx, And Configure The Passenger Module

Nginx, pronounced “engine x”, is “an HTTP and reverse proxy server, as well as a mail proxy server.” To put it simply, it is a versatile Web server that is low on resources.
Nginx and Passenger
In order to let Passenger install Nginx, you need to install a dependency first.
1$ sudo apt-get install libcurl4-openssl-dev
You can start installing Nginx and configuring the Passenger module by using the following command. Notice that we use rvmsudo instead of sudo, because the regular sudo does not work on this little program.
1$ rvmsudo passenger-install-nginx-module
The program will check the dependencies first and then ask whether you want the program to download the Nginx source code or to download it yourself. Choose option 1 (have the program download the Nginx source code for you), and hit “Enter.” You can leave everything in the default settings, so just make your way through the installation process.
In the end, you will be presented with two screens. The first shows how to configure Nginx to work with Passenger; this was already done by the program. The second shows how to configure Nginx to deploy an application. We will come back to this example later in the tutorial.
You could start Nginx by hand…
1$ sudo /opt/nginx/sbin/nginx
… but using a start-up script is preferable. (Because Nginx gets compiled from source, it does not come with a start-up script.) With a start-up script, we can not only start Nginx, but also stop, reload and restart it. In addition, Nginx will be started automatically if the VPS reboots unexpectedly. Therefore, we need to download a little start-up script for Nginx to the home directory using Wget. Wget is a simple command line program that enables us to download files from the Internet. You do not need to understand the rest of the commands. They simply move the script to the right location, make it executable and make sure that Nginx starts when the system boots.
1$ cd
3$ sudo mv nginx /etc/init.d/nginx
4$ sudo chmod +x /etc/init.d/nginx
5$ sudo /usr/sbin/update-rc.d -f nginx defaults
From now on, the following commands can be used to start, stop, reload and restart Nginx.
1$ sudo /etc/init.d/nginx start
2$ sudo /etc/init.d/nginx stop
3$ sudo /etc/init.d/nginx reload
4$ sudo /etc/init.d/nginx restart

Install PostgreSQL

PostgreSQL is “a sophisticated object-relational DBMS, supporting almost all SQL constructs, including subselects, transactions and user-defined types and functions.”
Install PostgreSQL together with a dependency. This dependency will be needed to install the “pg” Gem later on, which is responsible for the connection between PostgreSQL and Ruby on Rails.
1$ sudo apt-get install postgresql libpq-dev

Configure PostgreSQL

When the packages have been installed, move on to configuring PostgreSQL by securing psql. psql is the PostgreSQL interactive terminal, and it is used for administrative database tasks.
By default, you do not need a password to log into psql. We’ll change this by editing the authentication method and then reloading the PostgreSQL configuration. But first, assign a password to superuser “postgres”. Log into psql, assign a safe password to “postgres,” and then log out of psql.
1$ sudo -u postgres psql
2# \password postgres
3# \q
Now change the authentication configuration by changing ident to md5. This ensures that a password is needed to log into psql and that the password is encrypted. The two relevant lines, which need to be edited, can be found near the end of the configuration file. After that, reload the changed configuration into PostgreSQL.
1$ sudo nano /etc/postgresql/8.4/main/pg_hba.conf
2$ sudo /etc/init.d/postgresql reload
Most other PostgreSQL settings are stored in another configuration file. These settings can also be optimized, but that is beyond the scope of this tutorial. Keep in mind that the PostgreSQL configuration needs to be reloaded in order for the changes to take effect.
1$ sudo nano /etc/postgresql/8.4/main/postgresql.conf
The VPS is now installed. You can log out.
1$ logout

Testing The VPS

To make sure everything works, we’ll develop a very small application on the local development machine and deploy it to the VPS using Capistrano. This process consists of the following steps:
  1. Open two terminal windows, one for the local development machine and one for the VPS.
  2. Log into the VPS using SSH (VPS).
  3. Create a database user for the test application (VPS).
  4. Create a database for the test application (VPS).
  5. Create a test application using PostgreSQL as the database (local).
  6. Configure the database connections for the test application (local).
  7. Generate a simple scaffold for the test application (local).
  8. Initialize Git as version control for the test application (local).
  9. Add all the files of the test application to the Git version control list (local).
  10. Take a version snapshot of the current application using Git (local).
  11. Initialize Capistrano as a deployment tool for the test application (local).
  12. Remove the default Capistrano deployment configuration file, and create a new one (local).
  13. Set up the VPS to deploy the test application using Capistrano (local).
  14. Check the VPS set-up for deploying the test application using Capistrano (local).
  15. Deploy the test application with Capistrano (local).
  16. Edit the Nginx configuration to work with the test application (VPS).
  17. Reload Nginx (VPS).
  18. Check the test application in a Web browser (local).
Once we have verified that everything works, we’ll go through the following steps:
  1. Delete the database for the test application (VPS).
  2. Delete the database user for the test application (VPS).
  3. Restore the default Nginx configuration (VPS).
  4. Reload Nginx (VPS).
  5. Remove the test application (VPS).
  6. Log out of the VPS (VPS).
  7. Remove the test application (local).
  8. Close both terminal windows.
Unlike part 1 of this tutorial, some of these steps have to be performed on the local development machine, and other steps have to be performed on the VPS. Therefore, we will open two terminal windows on our local development machine: one for the local development machine itself, and one with a connection to the VPS. The conventions used to test the VPS are shown below in Box 2.1. The database user name and the database name are derived from the name of the application.
Box 2.1
Name of the application: test_app
Name of the VPS database user: test_app
Password of the VPS database user: banana
Name of the VPS database: test_app_production
Name of the VPS system user: johndoe
VPS IP address: 123.456.7.890
Now open two terminal windows, one for the local development machine and one for the VPS. Log into the VPS using SSH:
1$ ssh johndoe@123.456.7.890 (VPS)
When applications are deployed to a (publicly accessible) VPS, creating a new database user for every single application is good practice. This way, you will prevent multiple applications from viewing, inserting, editing and deleting data from and to each other’s databases, and thus increase security.
Let’s create a database user for the test application using the createuser command. We are using “postgres” as administrator (or superuser) for PostgreSQL. The P flag enables us to provide a password. The > sign stands for the questions that will be prompted.
1$ sudo -u postgres createuser -P (VPS)
2> Enter name of role to add: test_app
3> Enter password for new role: banana
4> Enter it again: banana
5> Shall the new role be a superuser? (y/n) n
6> Shall the new role be allowed to create databases? (y/n) n
7> Shall the new role be allowed to create more new roles? (y/n) n
8> Password: your-postgres-user-password
Then, create a database for the test application that is owned by the test application user. While you can use Rake to create a database, we will use PostgreSQL so that we can learn some basic PostgreSQL administration.
You can create a new database by invoking the createdb command in conjunction with the O flag, the database user name and the new database name itself. The production that we append to the end of the database name is the default name. Here, you will be prompted for the PostgreSQL superuser password again.
1$ sudo -u postgres createdb -O test_app test_app_production (VPS)
2> Password: your-postgres-user-password
Now that the database has been set up, it is time to create the actual Ruby on Rails application on your local development machine.
Navigate to your home directory, and create a new Rails application, named test_app and using PostgreSQL as the database back end. The d flag enables you to specify your preferred database software.
1$ cd (LOCAL)
2$ rails new test_app -d postgresql (LOCAL)
Go into the Rails application directory. Use Nano to edit the database configuration file by adding banana as a password in the production database configuration. Because we have followed the conventions described in Box 2.1, the database user name and the database name have already been taken care of.
1$ cd test_app (LOCAL)
2$ nano config/database.yml (LOCAL)
Now, generate a basic scaffold. Programming in Rails is beyond the scope of this tutorial, but this command will create a “User” model and a “users” controller. The inputs will consist of a name and an email address, which are both strings in the PostgreSQL database.
1$ rails generate scaffold User name:string email:string (LOCAL)
Remember when we set up Git in part 1 of this tutorial? Now we’re finally going to use it. We will initialize Git as version control for the test application, add all of the files from the test application to the Git version control list (recursively), and take a version snapshot of the current application using Git. The m flag lets us add a short description of the snapshot.
1$ git init (LOCAL)
2$ git add . (LOCAL)
3$ git commit -m “First commit” (LOCAL)
By now, it is time to deploy the application to the VPS, which we will do using Capistrano.
Initialize Capistrano as a deployment tool for the test application. This will create several files in your Ruby on Rails application directory. Remove the default Capistrano deployment configuration file, and create a new one. The contents of the new Capistrano configuration file can be found in Box 2.2 below.
1$ capify . (LOCAL)
2$ rm config/deploy.rb (LOCAL)
3$ nano config/deploy.rb (LOCAL)
Box 2.2
01# RVM
02 
03$:.unshift(File.expand_path('./lib', ENV['rvm_path']))
04require "rvm/capistrano"
05set :rvm_ruby_string, 'default'
06set :rvm_type, :user
07 
08# Bundler
09 
10require "bundler/capistrano"
11 
12# General
13 
14set :application, "test_app"
15set :user, "johndoe"
16 
17set :deploy_to, "/home/#{user}/#{application}"
18set :deploy_via, :copy
19 
20set :use_sudo, false
21 
22# Git
23 
24set :scm, :git
25set :repository"~/#{application}/.git"
26set :branch, "master"
27 
28# VPS
29 
30role :web, "123.456.7.890"
31role :app, "123.456.7.890"
32role :db"123.456.7.890", :primary => true
33role :db"123.456.7.890"
34 
35# Passenger
36 
37namespace :deploy do
38 task :start do ; end
39 task :stop do ; end
40 task :restart, :roles => :app, :except => { :no_release => true } do
41   run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
42 end
43end
Use the cap command to set up the VPS in order to deploy the test application using Capistrano. This will set up some directory structures on your VPS.
When using the cap command, you will need to provide a password when prompted. This is the password of the VPS user that you created at the very beginning of this tutorial. Check the VPS set-up for deploying the test application using Capistrano, and finally, deploy the test application.
Executing the last command might take a while because it installs the required Gems on the VPS and takes care of the database migrations (if there are any). Here you really see the benefit of Capistrano, because it automates tasks such as uploading the latest version of your application, installing the required Gems and performing the database migrations.
1$ cap deploy:setup (LOCAL)
2$ cap deploy:check (LOCAL)
3$ cap deploy:cold (LOCAL)
The last thing to do is tell Nginx where the Ruby on Rails test application is located. So, we need to edit the Nginx configuration file.
An example of the changes you have to make to that file are shown in Box 2.3 below. Only an excerpt of the relevant lines is printed here. Make sure to comment out the last four lines of the excerpt using #. Once you have made the changes, reload the new configuration into Nginx.
1$ sudo nano /opt/nginx/conf/nginx.conf (VPS)
2$ sudo /etc/init.d/nginx reload (VPS)
Box 2.3
(…)
01server {
02   listen 80;
03   server_name www.yourdomain.com;
04   root /home/johndoe/test_app/current/public;
05   passenger_enabled on;
06 
07   #charset koi8-r;
08 
09   #access_log  logs/host.access.log  main;
10 
11   #location / {
12   #    root   html;
13   #    index  index.html index.htm;
14   #}
(…)
When the deployment and Nginx configuration are done, check the application in a Web browser. Navigate to http://your-vps-ip-address/. The link to the application’s environment will not work in production mode.
Welcome
After that, look at http://your-vps-ip-address/users. Create, edit, view and delete some users:
Users
If everything has worked, then the test application database and the test application database user can be removed. The dropdb command removes a PostgreSQL database.
1$ sudo -u postgres dropdb test_app_production (VPS)
2> Password: your-postgres-user-password
The dropuser command removes a PostgreSQL user.
1$ sudo -u postgres dropuser (VPS)
2> Enter name of role to drop: test_app
3> Password: your-postgres-user-password
Restore the Nginx configuration by copying an example of the (default) Nginx configuration file, overwriting the modified one, and then reload Nginx.
1$ sudo cp /opt/nginx/conf/nginx.conf.default /opt/nginx/conf/nginx.conf (VPS)
2$ sudo /etc/init.d/nginx reload (VPS)
When that is done, navigate to your home directory on the VPS, and recursively remove the test application.
1$ cd (VPS)
2$ rm -rf test_app (VPS)
Finally, log out of the VPS.
1$ logout (VPS)
For the local development machine, we also need to navigate to the home directory and recursively remove the test application. When all of the commands below are entered, you can close both terminal windows. This leaves you with a fresh VPS and local development machine ready for developing and deploying Ruby on Rails applications.
1$ cd (LOCAL)
2$ rm -rf test_app (LOCAL)

Appendix

Linux Command Line Glossary

The Linux commands used in this tutorial are described here. The list is in alphabetical order and features only the relevant Linux commands. A Linux command usually takes the form of command -option(s) argument(s). For example, rm -r test_app. For a more detailed description, use the manual, which can be accessed using man [command].
  • sudo [command]
    Executes a command as an administrative user.
  • adduser [username]
    Adds a user to the system.
  • adduser [username] [groupname]
    Adds a user to a specific group.
  • apt-get dist-upgrade
    In addition to performing upgrades, this is used to intelligently handle dependencies.
  • apt-get install [package]
    Installs (or upgrades) packages.
  • apt-get update
    Resynchronize the package index files from their sources.
  • apt-get upgrade
    Installs the newest versions of all packages currently installed.
  • bash < <( curl [location] )
    A combination of commands used to both obtain and execute a script (from the Internet).
  • cd [location]
    Changes the current working directory. Without an argument, it goes to the user’s home.
  • cp [file] [location]
    Copies a file to the specified location (overwriting the existing file silently).
  • chmod +x [file]
    Makes a file exexutable.
  • logout
    Logs out of a shell or SSH session.
  • mv [file] [location]
    Moves a file to another location.
  • nano [file]
    Used to edit configuration files.
  • reboot
    Reboots the system.
  • rm [file]
    Removes a file.
  • rm -rf [directory]
    Removes a directory (recursively and forced, so it will not prompt).
  • source [script]
    Forces bash to read the specified script.
  • ssh [username@ipaddress]
    Logs into a secure shell session.
  • type [command]
    Displays the kind of command that the shell will execute.
  • wget [location]
    Obtains a file from the Internet.

Resources

Further Learning