Learning Rails: Resource Generation

Table of Contents

(Coming Soon!) Validations and Testing »

Last time, I saw how easy it was to create a new application using the rails new command. I learned a bit about controllers, views and routes, including how to create my own. Today, I’m going to learn about resource generation and data models, and create a crude URL shortener.

Generating Resources

A Rails application is organized around resources. A resource is simply the object the user of the application will interact with. I can let Rails generate my resources for me using the rails generate scaffold command. Invoke the command by passing the name of the new resource and a list of the properties. In this case, I am creating the ShortUrl resource with a single string property named url.

$ rails generate scaffold ShortUrl url:string
      invoke  active_record
      create    db/migrate/20111029050110_create_short_urls.rb
      create    app/models/short_url.rb
      invoke    test_unit
      create      test/unit/short_url_test.rb
      create      test/fixtures/short_urls.yml
       route  resources :short_urls
      invoke  scaffold_controller
      create    app/controllers/short_urls_controller.rb
      invoke    erb
      create      app/views/short_urls
      create      app/views/short_urls/index.html.erb
      create      app/views/short_urls/edit.html.erb
      create      app/views/short_urls/show.html.erb
      create      app/views/short_urls/new.html.erb
      create      app/views/short_urls/_form.html.erb
      invoke    test_unit
      create      test/functional/short_urls_controller_test.rb
      invoke    helper
      create      app/helpers/short_urls_helper.rb
      invoke      test_unit
      create        test/unit/helpers/short_urls_helper_test.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/short_urls.js.coffee
      invoke    scss
      create      app/assets/stylesheets/short_urls.css.scss
      invoke  scss
      create    app/assets/stylesheets/scaffolds.css.scss

The scaffold generator created everything I needed to start working with my resource including the controller, routes, views, model and database migrations.

Read the rest of this entry »

Smoke Free 250 Days

  • 250 days since my last cigarette.
  • 5000 cigarettes not smoked.
  • $1,375.00 not spend on cigarettes.

Until February, I had been a pack-a-day Camel Lights smoker for fifteen years. I logically knew that I should quit, but I still really enjoyed smoking. Despite many failed quit attempts over the years, I tried again in February. The first couple of days were rough and I don’t know if I would have succeeded if I hadn’t found help. On day two of smokeless misery I was at a party where a good friend was using an e-cigarette. Intrigued, I did some research and then desperately sought one the next day. It may be the best money I ever spent.

The e-cigarette has made quitting smoking easier than I could have imagined. It’s not even like quitting! It’s more like switching brands. Also, I:

  • Can use it inside.
  • Don’t smell like an ashtray.
  • Get more kisses from the wife.

Oh, and the lack of cancer is cool too.

If you want to quit smoking, and you should, give the e-cigarette a try.

Learning Rails: Application Generation

Table of Contents

In the last two posts, I installed Rails on both the Debian and Windows boxes.  If you want to read about how I did it and the problems I had to solve then check those posts out.  Now that Rails is finally installed I am ready to start writing my URL shortener.

Rails is a Model, View, Controller, or MVC, architecture. The models represent the data, and are commonly tied to the database objects. Views define the user interface of the application. Controllers provide the business logic by processing the requests, interacting with the models and then passing the data to the views for rendering. The MVC architecture isolates the user interface from the business logic, helping to create more maintainable code.

Generate the Application

The rails command is the heart of the Rails environment. It is used to create new projects, generate code, and run and debug the application. To start a new Rails application I’ll use the rails new APPNAME command, which generates the skeleton of a new application in the APPNAME directory.

$ rails new njeni.us
 create README
 create Rakefile
 Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
$ cd njeni.us

Read the rest of this entry »

Learning Rails: Installing Rails, Part 2 – Windows

Table of Contents

Last time, I installed Rails on the Debian box and had some trouble, but I got through it. This time, I’m going to install Rails on the Windows box.  This is my laptop that I have with me most often, so I need to develop from it, too.

Installing Ruby and RubyGems

To begin, I need Ruby on the machine, and luckily there is a Windows installer available. The RubyInstaller project is:

…a self-contained Windows-based installer that includes the Ruby language, an execution environment, important documentation, and more.

That’s handy. I download the latest RubyInstaller from here and run it.  I make sure to check Add Ruby executables to your PATH so I can use ruby and gem from the command line.

When it finishes, I open a command prompt to make sure it installed correctly.

C:\Users\Miller>ruby --version
ruby 1.9.2p290 (2011-07-09) [i386-mingw32]

RubyInstaller also installs RubyGems automatically, but it’s an older version.

C:\Users\Miller>gem --version

I update to the latest version using the gem update --system command.

C:\Users\Miller>gem update --system
Updating rubygems-update

C:\Users\Miller>gem --version

Installing Rails

The easiest way to install Rails is with RubyGems.

Read the rest of this entry »

Learning Rails: Installing Rails, Part 1 – Debian

Table of Contents

Before I can write code, I need to install Rails.  The best place to get started is the Ruby on Rails Download page. I work on both a Windows box and a Debian box, so I’ll need to install Rails on both machines. This time, I’m going to focus on installing Rails on the Debian box, which is actually the server where this project will eventually run. When I’m doing a lot of command line work, I prefer to work on the Debian box.

Installing Ruby and RubyGems

Note: I’m running a clean install of Debian Squeeze for this project. If you aren’t, your steps might differ. Follow the instructions at the Rails download page.

First, I install ruby.

$ sudo apt-get install ruby
Reading package lists... Done
Setting up ruby1.8 ( ...
Setting up ruby (4.5) ...

$ ruby --version
ruby 1.8.7 (2010-08-16 patchlevel 302) [x86_64-linux]

That looks good. Now I need RubyGems.

RubyGems is the standard package manager for ruby.  If you need a Ruby library, like Rails, there’s a good chance it’s available as a gem. So, I download and install the latest version.

$ wget http://rubyforge.org/frs/download.php/75309/rubygems-1.8.10.tgz
2011-10-19 21:49:25 (351 KB/s) - `rubygems-1.8.10.tgz' saved [249683/249683]

$ tar -xzvf rubygems-1.8.10.tgz

$ cd rubygems-1.8.10

$ sudo ruby setup.rb
RubyGems 1.8.10 installed
RubyGems installed the following executables:

That was pretty easy.

Read the rest of this entry »

FcgidMaxProcessesPerClass Broken on Debian Squeeze

The server went down today with an out of memory kernel panic when Natural Jenius was under heavy load.  I started watching the system, and we were getting a separate php5-cgi process for each simultaneous request.  According to the Apache documentation, FcgidMaxProcessesPerClass is supposed to limit the number processes spawned per virtual host.  the default value is 100, but for a server our size it should be at about 2. So I fired up vi to edit the configuration.

$ cat /etc/apache2/mods-enabled/fcgid.conf
AddHandler fcgid-script .fcgi
 FcgidConnectTimeout 20
 FcgidMaxProcessesPerClass 2
$sudo service apache2 restart
 Restarting web server: apache2 ... waiting ...

I used the Apache benchmark tool from another machine to test the configuration. I started with twenty requests, five simultaneously.

$ ab -n 20 -c 5 naturaljenius.com/category/programming
This is ApacheBench, Version 2.3
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking naturaljenius.com (be patient)...apr_poll: \
    The timeout specified has expired (70007)

What the…? When I checked the server, there were a boatload php5-cgi processes, one for each request. The server was extremely slow and running out of RAM quickly.

Read the rest of this entry »

Learning Rails: Introduction

Table of Contents

I’ve wanted to learn Ruby on Rails for a few years.  I like the simplicity and elegance of the framework and the resulting projects.  I have started to learn it in the past, but I always end up quitting because I don’t have something specific to work on.  This time I am starting with a plan to build something useful, and post the progress for the world to see.

The Plan

I will create a new project from scratch using Ruby on Rails and document the journey here.  For me, there is no better way to learn about new technology than to create something useful and write about it.

Along the way, we will cover:

  • Creating a project with rails.
  • Implementing something useful.
  • Writing tests.
  • Source control.
  • Deploying the application.

I will cover each step in the process with an individual post and I will try to keep everything short and simple.  I will deploy early and often.  Each version will be deployed separately and linked from the relevant posts so you can see the progress as we go.

The Project

I will create a URL shortener, njeni.us.  Why a URL shortener?  It’s a relatively simple project that I think fits well into this plan. It’s something I will actually use when I post links on twitter. And finally, it’s just plain cool to have my very own vanity short URLs!

I’m sure the project will evolve as I go, but here are the features I would like to see in the project.

  • Create a short URL.
  • Redirect clicker to site.
  • AJAX
  • Implement an API.
  • Track and display statistics.

Follow Along

If this sounds interesting, follow along.  You can see all the posts in this series at the Table of Contents, or subscribe to the blog to get the latest posts as soon as they are written.

I’d love to hear your comments and suggestions, so please let me know what you think.

New and Improved: Now Self-Hosted!

As I mentioned in my first post, I wasn’t happy with the shared hosting from GoDaddy.  It was slow, and I couldn’t stand the administrative interface.  I looked at all the popular alternatives, like HostGator, BlueHost and Dreamhost, but I worried that I would run into the same issues.  I was sixty seconds away from signing up with HostGator, when I came across Rackspace Cloud Servers in my searches.

With Rackspace, you get a VPS with your choice of OS that you can manage yourself.  You pay by the hour, and can scale up or down based on need.  I had always assumed something like that was too expensive, but it’s actually very affordable.  The entry-level box has 256M of RAM and 10G of drive space for 1.5 cents per hour.  That works out to just under $11 a month.

Their flexible billing is my favorite part of the deal.  There are no flat monthly charges.  You simply pay for what you use.  If you need a test box for two days to test something, you can create a new server in minutes and delete it when you’re done.  You will only be charged $0.72.

We actually have seven sites that need hosting, with more on the way, so it makes sense to get a VPS that we can manage ourselves.  We don’t need to worry that the other sites on a shared server will slow us down, and we can configure everything exactly as we want.  If we run out of room, we can increase the specs on our current machine or spin up an entirely new one

So after a long weekend scraping the rust from my Linux command line skills, Natural Jenius is up and running on a Debian Squeeze box running Apache and PHP5.  We are also using Cloud Files(more on that later) to serve up some of the static content, so the site should be pretty fast now.  Please let me know if you experience any issue with the site now that the switch has happened.

Dennis Ritchie’s Death

I somehow missed the news that Dennis Ritchie died on Saturday. For anyone that doesn’t know, he is the father of C, one of the most widely used and influential programming languages, and one of the inventors of the UNIX operating system. He was not only an influential figure in my life, but in the lives of anyone that uses a computer.

While my very first programming experiences were with BASIC, I didn’t really start to learn programming until I started to write in C. It taunt me to think like the machine, from the memory management to the CPU. I wouldn’t be the programmer I am today if I hadn’t learned C. I have such fond memories of working late on complex school assignments or the countless hours I spent programming MUDs in vi.

Steve Jobs’ death got all the press, but Dennis Ritchie helped lay the groundwork that became all of the devices we use today. Few people have such an impact on the world.

Now I just need to find my copy of K&R.

Onswipe iPad WordPress Theme

If you visit Natural Jenius on the iPad, you will notice our new iPad-specific theme powered by Onswipe.  Onswipe is a platform designed to make publishing look beautiful on tablet devices.  Their software powers the tablet-specific views for sites like Slate and The Blaze.  If you have a blog hosted at wordpress.com, you already have Onswipe ready to go, but if you have a self-hosted WordPress site you can install the plugin.

After installing the plugin, configure it from the Onswipe settings in the Appearance menu. You can choose how your images are displayed, change the font and select a color scheme.  Save your settings and that’s it.

Onswipe WordPress settings

Onswipe WordPress settings

Check out Natural Jenius on the iPad to see how it looks.  I will upload a screenshot later today.

Read the rest of this entry »