Category Archives: Ruby / Rails

Another Installing Ruby and Rails on Ubuntu 14.04 Post

I’ve done it again… Needed to setup an Ubuntu machine to run a simple CRUD web app I maintain for a small ministry group. The app is built on Rails 3.2.8, Bootstrap 2 UI, Ruby 1.9.3, and uses SqlLite for a local single-file database. I began writing the app in April 2012, with small tweaks here and there each year since. It was my first real Rails app, and it still runs fine today as a contact management system for the 5-person distributed team who use it to track their ministry contacts and record various interactions they each have with their members.

I needed to move the app off of my own network which has plenty of internet and power outages throughout the year, so I decided to go with a cloud hosted option and chose Digital Ocean and one of their small “droplet” containers running a ready-to-use Ubuntu 14.04 system. I am able to get by with 1GB RAM AND 20gb storage, so the cost is $10 per month. Once the droplet is created using their very simple web portal, you get nothing more than a Linux box that you can access via SSH, VNC, or a terminal client like Putty (I installed Putty on my Windows machine using Chocolatey). It’s all terminal windows from there; no GUI at all.

So, to install Ruby and Rails, I logged into my droplet via a Putty terminal session and I followed one of the Digital Ocean help docs on how to install Ruby. It has you install RVM, and from that you can install the Ruby version that your app needs (in my case ruby-1.9.3-p392).

Here’s the RVM setup link from Digital Ocean: https://www.digitalocean.com/community/tutorials/how-to-install-ruby-on-rails-on-ubuntu-14-04-using-rvm

Then I installed git so I could clone the source code repo of my app from my BitBucket account:

Then I had to install the Bundler gem so I could install all the other gems my apps needs to run:

To install the other gems in my app’s bundle list:

One snag… While all the gems were installing during “bundle install”, I got some error with the “nokogiri” gem, complaining that “libxml2 is missing“. I found a post on StackOverflow that showed my how to fix this problem:
http://stackoverflow.com/questions/6277456/nokogiri-installation-fails-libxml2-is-missing

Next, I ran “bundle install” again, and this time all gems installed fine.

So, now I tried to run my app using the built in Rails server:

and I got an error that something in the app “Could not find a Javascript runtime“, so, back to StockOverflow from a google, and I learned how to fix this issue:
http://stackoverflow.com/questions/16846088/rails-server-does-not-start-could-not-find-a-javascript-runtime

So, finally after all this hacking around in the terminal window, the app ran fine using the built in Rails “WEBrick” server, which is all I need to host my app for about 5 users.

UPDATE: How to keep the WEBrick web server process running after I shut down the Putty console session I used to remote in and start up the app

I had used the Putty terminal app to remote into the VM droplet and start up the app using the rails command listed above, but when I closed the terminal session, the app process was killed and no one could access it from their web browsers. So, I found a StackExchange post that explained how to run a process in the background and tell it to ignore the shutting down of the terminal session so it would stay alive even after the terminal session ended. Here’e the link: http://unix.stackexchange.com/questions/479/keep-ssh-sessions-running-after-disconnection

This “nohup” command starts a process and tells it to “ignore the hang up command when the terminal session is ended“, and we can also add the the “&” command line flag which means “run the process in the background“. With this we can now exit the terminal session and the process will continue running to server web requests.

Command:

As long as you are in the same terminal session as you started the process under, you can use the “jobs -l” command to see the running background process that you just started and see the process id. (Important: You’ll need the process id whenever you need to stop the Rail/WEBrick web server. Keep reading below…)

Here’s the output:

Now you can quit the terminal session, but the app will still keep running, so users can access the web app from their browser.

If you close this terminal session and log in later with a new terminal session later, it’s a little harder to find the process id of the Ruby/WEBrick session that you started in the original terminal session. However, we can find the process id using this command (notice we are running the output from “ps” through grep and filtering with “ruby” so that we will see only the ruby processes. You could also filter on “rails” just as well:

Stopping the process

Now, when you need to end (kill) the process to stop it, you have to know the process_id and use a special flag on the kill command, because the NOHUP command used to start the process will cause it to ignore the kill command. The command is: kill -9 [proceess_id]. (See notes above on how to learn the correct process_id.)

See this link for more info on this matter: http://stackoverflow.com/questions/8007380/how-to-kill-a-nohup-process

So:

Another update…FTP access

A few days later I wanted to FTP upload some files to my Droplet on Digital Ocean. So, I found this really simple help post on the Digital Ocean community forum. It explains how you can use FileZilla and the SFTP secure protocol to easily connect to your Droplet from a FileZilla client session running on your local machine. There’s no configuration required in your droplet; it was built-in and ready to use on my Ubuntu 14.04 droplet that I based my VM on). Here’s the link: https://www.digitalocean.com/community/questions/how-i-get-ftp-login-with-filezilla

Yee-haw!!!

Now, let me get back to my .Net/C#/Sql server/Entity Framework/MVC etc…

Hosting your own Rails apps

Sometimes the current options for paid hosting of Rails apps are just not warranted for small scale apps. Imagine a small business app where there may only be 10 or 15 users across the whole country. These are small, but very real CRUD apps that need to be accessed from a web browser by remote users, it’s just that the user count may be small. Let’s face it, not every site in the world gets a million hits a second, right?  Sometimes the cost of paid hosting options is too much for these little apps, which can cost $50 to $75 a month even for the smallest hosting package. For big corporations this is no big deal, but for small mom-and-pop companies or small organizations, it’s still too much.

So, being a simple and frugal guy, I have been able to successfully host a few of these small, private login apps right in an Ubuntu Linux virtual machine that I am running inside of a Windows XP box sitting right on my local network.

Yep… A Windows XP machine running Virtual Box which has Ubuntu 10, where I used RVM to install Rails and all the Gems for the app. Then I go to a terminal window and start up the Rails development web server on a certain port, and leave it running. In most cases, the database is SQLite, but you can use anything that you can get running in your development environment. SQLite is plenty powerful enough for this small user-count scenario, even if the database is or becomes large (1GB, 5GB is no problem for SQLite). 

Most of my apps do user authentication to validate the users at login. Myself or an admin for the app are the only ones who can create user accounts . The total number of daily users is usually less than 20 or so, and it is not open to public signup. It’s a low volume, privately accessed app.  So, the developer environment of a simple Ubuntu / Rails machine handles it very well. The users have no idea what is happening on the back end.

I have the XP machine on a battery backup, and I have a static public IP with my business-grade internet service provider.

To handle the hits, I redirect from my main public facing router (switch) to the LAN based IP and port which the Ubuntu VM uses.

So, my users enter an address like this to hit their app (notice that a specific port is requested):

(the above is a fake address, but you get the picture)

When this hits my public facing router, I redirect  it to the Ubuntu Virtual Machine LAN IP and the port that I used when I started the Rails development server:

So, with this mapping in place, I go to the virtual machine and open up a terminal, CD to the Rails app directory, and enter:

to start up the server on port 3003. (You can use any free port that you have available.)

image

 

Boom! A live self-hosted Rails app. 

You can run as many of these as you want. Even in the same VM you can run different ones just by change the port that is used for the Rails server, and then just create a new mapping on your switch.

Sure, since I am using SQLite, it’s single threaded hits to the database file, but hey, for what little traffic this thing gets each hour, it handles it very easily, and the users never feel any speed issues.

 

Pros: Free, full control, hands-on, dang… it just works! Trust me, I’ve been doing it for months!!!

More Pros: Because it’s a VM , about 20GB is enough size, and you can backup or clone the entire machine as a single file.

Cons: Keeping the host XP machine and the VM alive all the time, keeping my internet connection alive, keeping the Ubuntu updates applied (if needed), backing up the data file(s).

Installing RubyMine 4 on Ubuntu 12.04

I recently set up a new Ubuntu 12.04 machine in a VirtualBox VM. After installing the basic RVM, Rails, and Ruby stuff, I was then ready to install RubyMine. (By the way, see this post where I explain how to setup the Rails goodness on a new Ubuntu 12.04 machine: http://mattslay.com/installing-rails-on-ubuntu-12-04-with-rvm-support/ )

Installing RubyMine

There is no actual “installer” for RubyMine on Linux. You just extract it to a folder of your choice. (I put mine in /home/matt/apps/RunyMine-4.0.3/). If you try to place it in one of the more locked-down system folder, you could run into permissions problems, which always drives me nuts. So I just create and “apps” folder in my Home folder, and drop all my non-Ubuntu-Software-Center packages in separate folders there.

You can read the RubyMine Installation Instructions in the file named “Install-Linux-tar.txt” file which is located in the archive file for RubyMine that you will download from JetBrains. (http://www.jetbrains.com/ruby/download/).  It will tell you where to unzip the files, and how to launch RubyMine after you’ve extracted it from the archive. (Note to Windows users… All this talk about “tar” and “archive” is basically what us Windows folks call a “zip” file.) After you download the archive from the JetBrains site, right click on it and open it with the Archive Manager. From there you can extract it to a folder of your choice. After that, it’s ready to run RubyMine (well, after you follow the next step…)

Sun Java JDK

RubyMine requires the Sun Java JDK environment to make its fancy GUI stuff work (note: RubyMine does not work well with OpenJDK, so don’t use this one by mistake!). Unfortunately, the Ubuntu Software Center does not have a click-easy installer for this, so you’ve got to do it in a terminal window, but trust me, it’s not hard. I followed this guide (from a Question/Answer on StackOverflow) to install the Sun Java JDK 1.7.0 in my new Ubuntu machine:

http://stackoverflow.com/questions/10178601/rubymine-on-linux

Note: This step can be done before or after you extract RubyMine from the .tar download. It’s just that RubyMine will give you an error if you try to run it without having the Sun Java JDK installed.

Done!

With Rails and Ruby installed (see link at the top of this page) and RubyMine extracted, and Sun Java JDK installed, you are ready to ride on the Rails train.

Installing Rails with RVM support on Ubuntu 12.04/12.10 or Linux Mint 14

Here’s a link to a really complete post on preparing your Ubuntu machine for Rails development:

http://railsapps.github.io/installrubyonrails-ubuntu.html

The above link by the awesome Daniel Kehoe should be all you need to get Rails running on your Ubuntu machine, but I’ve left the information below as a record of how I previously prepared my Ubuntu machines for Rails development. As of 2013-03-18, these instructions also worked well on a new Linux Mint 14 install box (which is based on Ubuntu 12.10).

I mostly followed this guide “Installing Ruby on Rails on Ubuntu 12.04from The Tech Journal, which worked very well, except for the RVM instructions did not work for me.

Since I had a trouble installing RVM per the instructions in the above post, I followed the basic install instructions directly from the full RVM site:

https://rvm.io/rvm/install/

Install RVM/Ruby dependencies

Next, from the terminal window, type:

RVM will show you a list of dependencies that need to be installed. So, run the sudo apt-get commands shown (copy and paste them in the terminal window) to prepare the environment for rvm, ruby, rails development.

Install a version of Ruby:

I can’t tell you which version(s) you’ll want or need, but this how you will install them.
You can get a list of available versions with this command:

You’re on you on from here…

Create a RVM gemset, then install your desired Rails version and any other gems your app needs. You’ll probably use the “bundle” command to pull in the required gems from a gemfile. From here on, it’s basic Rails stuff.

Other crap I’ve had to deal with if something goes wrong….

http://stackoverflow.com/questions/9056008/installed-ruby-1-9-3-with-rvm-but-command-line-doesnt-show-ruby-v/9056395#9056395

Oh, yeah, one more final point about (not) installing gem docs…

I always like to turn off the documentation downloads (rdoc and ri) when installing new gems (I never read the docs locally this way, I always use the web). You can make a permanent change on your system to *not* install gem documentation when installing new gems. Run this line in the terminal window:

This will create a .gemrc file in your home folder telling the gem installer not to download the docs when you install new gems. You only need to do this once.

Do this before you run any “gem install” commands, or use Bundler, so that it won’t waste time and space pulling down docs for the gems.

Other detailed instructions for installing a full Ruby, Rails, Apache, MySql stack

If you really want a LOOONG tutorial that also gets deep into installing Apahce, MySql, and all that jazz, check out this post which has a 35 page PDF mega walk-through.

Setting up RubyMine

If you want to install RubyMine IDE for your Rails development, you can follow my instructions here: http://mattslay.com/installing-rubymine-4-on-ubuntu-12-04/

Other goodies I installed on my new Ubuntu machine:

I installed these personal favorites right from the Ubuntu Software Center  (I’ve listed links so you can learn more about these tools, but I recommend installing them through the Ubuntu Software Center right inside of Ubuntu):

If you’ve got favorite Linux/Ubuntu tools that you think are helpful to Rails developers, please add them in the comments.

Manual setup steps for Devise gem in Rails

Here is the text displayed from running the configuration command line for the Devise authentication gem in rails.

Running this command:

Generates this text:

Some setup you must do manually if you haven’t yet:

1. Ensure you have defined default url options in your environments files. Here
is an example of default_url_options appropriate for a development environment
in config/environments/development.rb:

config.action_mailer.default_url_options = { :host => ‘localhost:3000’ }

In production, :host should be set to the actual host of your application.

2. Ensure you have defined root_url to *something* in your config/routes.rb.
For example:

root :to => “home#index”

3. Ensure you have flash messages in app/views/layouts/application.html.erb.
For example:

<p class=”notice”><%= notice %></p>
<p class=”alert”><%= alert %></p>

4. If you are deploying Rails 3.1 on Heroku, you may want to set:

config.assets.initialize_on_precompile = false

On config/application.rb forcing your application to not access the DB
or load models when precompiling your assets.

 

Ruby on Rails Support Discontinued in NetBeans IDE

I received this e-mail today (2011-01-27) about the end of Ruby on Rails support in NetBeans…

Here’s a link to the announcement on their website: 

http://netbeans.org/community/news/show/1507.html

This doesn’t surprise me at all, and I’m glad I switched to RubyMine a few months ago! I’ve noticed the Ruby/Rails forums on the NetBeans have been really dead for a while now, and I had already seen the in-house development going down hill.

So, here is the e-mail I received:

From: [===== (Update: 2011-01-27) I blanked out his part to protect the sender, at their request =======]
Sent: Thursday, January 27, 2011 4:39 AM
To: undisclosed-recipients:
Subject: Important Message: Ruby on Rails Support Discontinued in NetBeans IDE

Dear NetBeans Community:

After thorough consideration, we have taken the difficult step to discontinue support for Ruby on Rails in the NetBeans IDE. Two main issues underpin this decision:

Java SE 7 and Java Development Kit 7 (JDK 7) are the next major releases of the Java SE platform, which Oracle is committed to deliver in 2011. A key objective of the NetBeans IDE has always been to offer superior support for the Java platform. To maintain that objective and capitalize on the JDK 7 release themes–multi-language support, developer productivity and performance–it is necessary that our engineering resources are committed to a timely and quality release of NetBeans IDE 7.0.

Second: Although our Ruby support has historically been well received, based on existing low usage trends we are unable to justify the continued allocation of resources to support the feature.

As of January 27, the Ruby on Rails module will be gone from development builds of NetBeans IDE 7.0. Developers who want to continue to use Ruby on Rails functionality in the NetBeans IDE should please visit the NetBeans Ruby Support page for details on how to do so going forward.

We remain committed to delivering a first-class product to our community of developers and users, and we encourage your feedback on our mailing lists and forums, on Twitter, or by writing to us.

Thank you for your continued support of NetBeans. 
The NetBeans Team

Rails Installer for Windows

There’s a new way to Install Ruby and Rails on a Windows Machine

I wanted to make a small post to point you curious Windows developers over to the new Rails Installer for Windows web site (approx January 18, 2011), which was recently put online by Engine Yard, and is headed up by Wayne Seguin, the author of the popular RVM gem. The site shows three simple steps that will have your Windows box up and running with Ruby and Rails in just a few clicks. There is even a brief 3-minute video showing you just how simple it is to follow the steps and generate your first Rails 3 app in just minutes.

Next, you need an editor…

I think what the did is great; however… I think the stopped one step too soon. They get Ruby and Rails installed on your Windows machine, and show you how to generate your first app, but they stop short of showing you how to edit the Ruby and Rails source code files to actually finish building an app. Most hard core Rails devs are Linux or Mac users, and they eat, breathe, and sleep in a terminal window or some other (weird) text editor to do the actual coding. By now in my coding career, I know that every dev has his or her own favorite editor, and that’s fine; I have my own favorites too.  You could go really hard-code on the Windows platform and use Notepad plus an Explorer window. However, I think that if a new Rails on Windows users does jump on board, they will come out better choosing one the available code editors or IDEs to make their coding experience better.

You can gain a lot of insight about a Rails app just by seeing a visual of the folder structure that you get in a generated rails app. That’s the first thing you need to get your brain around as you start studying Rails. From the folder structure, you will edit the code for various Rails resources (i.e. the Models, the Views, and the Controllers), as well as a handful of config files for a Rails app.

You should check out each of these to see which one you like best: Ruby Mine IDE, RedCar, NetBeans, Komodo IDE, E editor(similar to TextMate)

So, finally, here’s a screen shot of the folder structure for a basic Rails app. (What you see here is in my RubyMine IDE). Those 3 red arrows point to the main folders for Models, Views, and Controllers. You’ll spend a lot of your time working on files in these folders. Also, notice that these folders are subfolders of a folder named “app”. 

So, be prepared to study the various Rails IDE or editors. My personal favorite is RubyMine.

So, check out the Rails Installer for Windows at http://railsinstaller.org/ to start your journey on the Rails path to coding goodness.

Rails Authorization and Authentication

Some developers confuse the terms Authentication and Authorization. At first, I also kind of lumped them both in the same bucket. Eventually, I figured out the differences, and wanted to address the issue here to help clarify things a bit.
Definitions:

User *authentication* is looking them up in the Users database to ensure they have an account in your system.

User *authorization* is a system of determining what areas of your app the User can access once they are authenticated into the site. 

I use two popular Rails gems that pretty much give you a drop-in solution for authentication and authorization. Devise is a Rails gem for User Authentication, and CanCan (by Ryan Bates of RailsCasts fame) is for User Authentication.
I ran across these great articles on another blog that describes using Rails and CanCan together:

Article 1: Getting Started with Devise and CanCan The article includes very detailed steps and code samples for both Devise and CanCan. 

Article 2: Devise and CanCan – Restful Resources for Administrators

You can also read my blog post about Getting started with Devise, which includes lots of other helpful Devise links to get you started.

HAML example

I wanted find out for myself what the reported HAML goodness is all about, so I spent a little time to educate myself on the basics, and then I took to converting one of my Rails erb files over to HAML. I’m posting the before and after results here as HAML examples to give one more convincing example of how much easier it is to read and write HAML views than the more noisy erb you-must-close-every-tag format.
At the end of this article, I list a few links to resources I found useful as I was getting started with HAML in my Rails application development.

Before (erb):

After (HAML):

More HAML examples and links

Some Thoughts on HAML by Rob Conery

Daniel Fischer says HAML is beautiful poetry

This article by Eric Davis exposes why he thinks HAML is bad, so you may want to study what he has to say

HAML cheat sheet

another HAML Cheat Sheet on http://cheat.errtheblog.com

HAML questions on StackOverflow

HAML user group on Google

http://www.rubyinside.com/haml-a-new-view-template-language-for-rails-235.html

http://haml-lang.com/

Learn more about HAML on Wikipedia

Latest HAML links on Coder I/O

Use this tool to automatically convert erb and html to HAML

HAML Videos

A video on HAML by Jason McCay from BarCamp Birmingham 2008-04-12

A HAML video from John Schult at merb day Atlanta 2008-12-06

HAML and SASS video (2007-11-20) – http://www.podcast.tv/video-episodes/episode-038-haml-and-sass-in-15-minutes-5214343.html

HAML and SASS video on Doctype video podcast Episode 38

Devise authentication for Rails

I am proud to report that I have successfully installed and used the Devise authentication gem in my little test app that I am building learn Rails. I’m still a newbie at all this stuff, so anything that I can “gem install” and then hack my way through configuring and actually see the thing work in my app always brings a smile to my face. The Introducing Devise (#209) and Customizing Devise (#210) screencasts on RailsCasts.com really helped me a lot by showing how simple it is to set it up and do some customization. Plus, the documentation for basic configuration and use is pretty easy to follow. That’s always a good thing to see in these gems. Since I’m still playing around on Rails 2.3.5, I had to use version 1.0.7 of Devise, but they do have a Rails 3 version on the download page too, so be sure you use the right version.

With Devise in place in your app (it only requires a few lines to configure it, see the documentation on the web site for how to set it up), not only can you handle all the basic needs of authenticating a user login from your Users table (without writing as single line of code!), it also gives you built-in functions to create new user accounts, emailing them their forgotten password, and letting them change their password while logged in.  Beyond those basics, you can then easily restrict access to certain parts of your app to only those users of a certain role. You simply create a Model for each role that you want to work with in your app.

I originally found some code samples for a roll-your-own authentication approach on the Building a New Web Site with Rails blog post over at a ThinkingInRails.com, and it did show me how to approach this if I wanted to have and maintain my own code base for this matter, but I really wanted to use a ready-made solution for this so I could move on to other matters in my Rails learning.
So, at this point, I must say that I’m going with the Devise gem for authentication in my Rails apps (like I have a lot of Rails apps, but hey, this thing is a great way to go when that does happen).

Other Devise resources: