eddorre

Found 21 posts tagged with 'rails'

Tutorial: Filtering results with jQuery UI Slider and Rails

Thursday November 05, 2009 21:16 | comment icon 0 Comments

At Planet Argon, we’re using the jQuery UI slider to filter results on one of our client projects. Since I had never implemented anything with jQuery UI slider, I decided to whip up a quick prototype just to see how it worked. It took me a little under an hour to get something put together. This post is the result of that prototype.

First of all, let’s visualize what we want to achieve. In my example, I have 20 dummy stocks that I want to filter down based on a high and low price. Here is a sample screen shot:

stocks

We’re going to start from scratch from a brand new Rails project. So we’ll have to create it:

NOTE: This tutorial uses Rails 2.3.4 but it can be easily adapted to work with recent earlier versions.

rails jquery_slider_rails

Since we’re using jQuery instead of Prototype, we’ll want to install the jRails gem. While we’re installing gems, we’ll install a gem called Faker to create some dummy names.

sudo gem install aaronchi-jrails --version=0.5.1
sudo gem install faker

In order to use them, we’ll have to add config.gem statements to our environment.rb file.

  config.gem "faker"
  config.gem "aaronchi-jrails", :lib => false, :version => "0.5.1"

Next thing we’ll have to do is go to the jQuery UI download page and we’ll download a custom build of jQuery UI. For this example, we’ll go lightweight and just select UI core and slider. I chose UI Lightness as the theme, but you can choose whatever you like; the theme won’t impact the results.

Once you download the files, place them in the following locations:

  • Images
    • /public/images/
  • jQuery and jQuery UI Javascript files
    • /public/javascripts/
  • CSS file
    • /public/stylesheets/

Now that we have all of the supporting files that we’ll need we’re ready to create our model that holds Stock information.

NOTE: Although I’m creating RSpec models and controller, I’m not writing any specs for this simple app. Perhaps that’s a post for another day.

script/generate rspec_model stock name:string price:integer

It’s probably a good idea to add an index on the price attribute since we’re going to be filtering on it.

Open up the db/migration directory and edit the only migration file to add the index. It should look like this when we’re done:

class CreateStocks < ActiveRecord::Migration
  def self.up
    create_table :stocks do |t|
      t.string :name
      t.integer :price
      t.timestamps
      
      t.index :price
    end
  end

  def self.down
    drop_table :stocks
  end
end

Now that we have the migration, we’re ready to create our database and run said migration:

rake db:create:all
rake db:migrate

We should have a running database now (on SQLite) but now we need some data. We’ll mis(use) the seed file functionality that was added in Rails 2.3.4. You can find the seeds.rb file in the db directory.

We want 20 dummy stocks with fake names and fake prices. For fake random names, we’ll use the Faker gem. The Faker gem comes in really handy for writing specs/tests. A topic that I’ll probably cover soon. For random prices, we’ll just use Ruby’s rand method.

20.times do |x|
  Stock.create(:name => Faker::Lorem.words(1).to_s, :price => rand(5 * (100)))
end

Once we save the file, we can load up our data by running the following command:

rake db:seed

Once the sample data has been seeded we can start building our model. We know that we want to filter the data based on two points on the slider. This can easily by done by a named scope that takes two arguments.

named_scope :filter, lambda { |low, high| { :conditions => { :price => low..high } } }

We’ll also need to grab the highest and lowest prices to plug in as max and min values into the slider. For that we can create a class method that returns each price in an array.

  def self.high_low_prices
    [Stock.minimum(:price), Stock.maximum(:price)]
  end

Let’s move over to our controller. We know that we’ll need an index action but we’ll also need some sort of action to respond to slider ‘stop’ events. We can easily create a filter method/action in the controller, but as it turns out we can actually re-use the index action and remain fully RESTful.

Let’s focus on getting the correct data. We’ll be passing in the two points from the slider as parameters. If both of those exist, we’ll actually call our filter named scope. If not, we’ll just grab all of the stocks.

    unless params[:low] && params[:high]
      @stocks = Stock.all
    else
      @stocks = Stock.filter(params[:low], params[:high])
    end

We can probably grab the highest and lowest stock prices from the stocks instance variable, but let’s be explicit.

@price_range = Stock.high_low_prices

If the request is not an ajax request we’ll load the index view. If it’s an ajax request, let’s replace our stock list with the filtered list.

    respond_to do |format|
      format.html
      format.js do
        render :update do |page|
          page.replace_html 'x_stock_list', :partial => 'stocks/stock_list', :locals => { :stocks => @stocks }
        end
      end
    end
  end

We can use the replace_html method here because we’re using the jRails gem.

We’re now ready to tackle the views.

Create an index.html.erb view under /app/views/stocks/. While we’re at it we’ll create the partial that we alluded to in our controller. We’ll call this _stock_list.html.erb and it goes into the same directory as the index view.

Add the boilerplate stuff to the index.html.erb view; a DOCTYPE, html, head, and body tags. I also added an h1 tag wrapping the word Stocks.

Remember those jQuery files that we downloaded a while ago? We’ll link to them now.

  <head>
    <%= stylesheet_link_tag 'jquery-ui-1.7.2.custom.css' %>
    <%= javascript_include_tag 'jquery-1.3.2.min.js', 'jquery-ui-1.7.2.custom.min.js' %>
  </head>

Inside the body tag, we’ll create a div so that our slider can hook into it. NOTE: I use inline styles here because this is a quick and dirty example. Please keep all styles in CSS files in a real app.

I also have gotten in the habit of prepending all classes and IDs that are used by Javascript and ajax interactions with ‘x_’. This is a convention that we use at Planet Argon. Robby Russell originally blogged about this in the article Designers, Developers, and the x_ Factor

    <div id="x_slider" style="font-size:62.5%; width:350px;"></div>

I follow the slider div another div for the high and low prices.

     <div>
       <p>Showing all stocks between <span id="x_low_selected"><%= @price_range.first %></span> and <span id="x_high_selected"><%= @price_range.last %></span></p>
     </div>

The last HTML elements on the page is the stock list itself.

    <ul id="x_stock_list">
      <%= render 'stock_list', :stocks => @stocks %>
    </ul>

Before we get to the jQuery code, let’s jump over to our partial and flesh it out. The code necessary is minimal.

<% @stocks.each do |stock| %>
  <li>
      <p><%= stock.name %></p>
      <p><%= stock.price %></p>
  </li>
<% end  %>

The jQuery UI slider library takes care of most of the heavy lifting. Here is the final slider Javascript code with an explanation below it of all of the settings.

    <script type="text/javascript">
      $(function() {
        $("#x_slider").slider( { 
          range: true,
          step: 10,
          max: <%= @price_range.last %>,
          min: <%= @price_range.first %>,
          values: [<%= @price_range.first %>, <%= @price_range.last %> ],
          stop: function(event, ui) {
            var prices = $('#x_slider').slider('option', 'values');
            $('#x_low_selected').html(prices[0]);
            $('#x_high_selected').html(prices[1]);
            $.ajax({
              type: "GET",
              data: ({ low: prices[0], high: prices[1] }),
              url: 'http://0.0.0.0:3000/stocks',
              dataType: 'script'
            });
          }
        });
      });
    </script>

Before we bind the slider to our div, we’ll wrap everything in a convenience function to make sure that the DOM is loaded.

Next we bind the slider by simply writing:

$("x_slider").slider( { options here }

As you can see in the code above, the slider takes several options (see full documentation for all options):

  • Range
    • When this is set to true, you’ll get two or more points on the slider
    • Step
    • This is the value that the slider decrements or increments every time you move a point
  • Max
    • The maximum value of the slider
  • Min
    • The minimum value of the slider
  • Values
    • An array of low and high points on the slider
  • Stop
    • This is an event that is fired when a point on the slider stops moving

In the stop event there is a bunch of stuff going on. First, I set a price array to the set points on the slider so I can use them later for updating the user of the min and max values as well as passing those in as parameters to the ajax call.

This code snippet simply replaces the min and max values on the page:

$('#x_low_selected').html(prices[0]);
$('#x_high_selected').html(prices[1]);

The ajax function also has several options:

  • Type
    • This is the type of HTTP request. A simple GET request will do here
  • Data
    • These are the variables that we’ll be sending along
  • URL
    • This is the URL that we’ll be hitting – this assumes that you’ve started the web server using script/server or mongrel_rails
  • DataType
    • I originally set this to html thinking that is what I wanted, but that’s the wrong call. You’ll want to use script if you want to return fragments of HTML otherwise you’ll return the whole page in HTML form (layout and all).

That’s it. As I said before, to test it, you’ll want to start up a web server with either mongrel_rails, script/server or Passenger. In your web browser, you should be able to go to either http://0.0.0.0:3000/stocks or http://jquery_slider_rails.local/stocks if you’re using Passenger to see the results.

I’ve made all of the code available for this tutorial on GitHub.

Canonical URLs

Tuesday April 14, 2009 02:09 | comment icon 2 Comments

Canonical URLs are all the rage on the Internet nowadays. All one has to do is do a Twitter search for canonical to see the conversations going on.

The problem is this, micro-blogging services such as Twitter only allow a certain number of characters, so a URL like this http://eddorre.com/posts/buildin-the-blog-part-5-refactoring-part-2, is too long. This is where URL shorteners like tinyurl.com come in.

They take a long, but perfectly fine URL, and make it something like this: http://tinyurl.com/Hukjfd (this is an example – not a real link). This is much more useful on Twitter where character space is at a premium. However this has its own problems, one is trust. How can you trust tinyurl.com to actually be delivering you to a URL that you would even want to visit? Short answer, you don’t. Also, what happens if tinyurl.com goes away one day? Any search on Twitter that uses these links immediately becomes less valuable. It’s the opinion of some on the Internet, that a site should take care of its own short urls.

For example, the link http://eddorre.com/posts/buildin-the-blog-part-5-refactoring-part-2, could become http://eddorre.com/s/SQ2BAs. Notice that the domain remains the same and short url is under my control. If the link goes away it’s MY fault not someone else’s. I have a vested interest in making sure that the link doesn’t go away. It doesn’t solve the trust issue, but at least you know that it’s a link coming from eddorre.com instead of anywhere on the Internet.

Enter the debate about canonical URLs and rev=canonical. The theory behind rev=canonical is simple. When I include a link like this: http://eddorre.com/posts/buildin-the-blog-part-5-refactoring-part-2 in Twitter or a similar website, they will then load up the original link and look inside the HTML for markup that looks like this:


<link rev="canonical" href="http://eddorre.com/s/SQ2BAs" />

When Twitter or a similar service finds this tag, they should then replace the long link with the short one. It makes sense but this does have one drawback that will most likely kill its adoption. It’s expensive. Twitter, for every link that is posted, has to connect to the URL, parse the HTML and then return a new link if it supports canonical URLs.

With that in mind, there is a proposed new HTTP header for canonical URLs that a web server could return to a service like Twitter. Something like “X-Rev-Canonical: href=”http://eddorre.com/s/SQ2BAs". This way, Twitter or other services just have to do a GET request to the original URL and it would just return them the short URL. No downloading and parsing the HTML. Whether either of these methods becomes widely adopted remains to be seen.

This past Saturday, after reading comments in Twitter and blogs about short urls, I decided to try coding up my own system for my blog. Turns out it only took me about 15 minutes to code something in Ruby/Rails.

Here is how I did it.

  • I created a migration to my posts table to include a short_url column
  • Created a before_create callback method in my post model to create a short_url.
  • The creation of the short_url is done by randomly mixing 6 characters from the characters available in Base 62 encoding (meaning: 0-9, A-Z and a-z).
  • To create short_urls for all of my older blog posts, I just created a migration that looped through all of the blog posts and generated this random token string for all of those and saved them.

I create a named route similar to the following:


map.short_url "/s/:short_url", :controller => 'posts', :action => 'show'                                   

Next, in my controller I did something similar to this:


    if params[:short_url]
      @post = Post.find_by_short_url(params[:short_url])
      redirect_to post_path(@post), :status => :moved_permanently and return
    else
      @post = Post.find_by_permalink(params[:id])
    end

There you have it. Something quick and dirty in about 15 minutes. Now if I want to post links to my blog on Twitter, I can use my own short url instead of using a service like tinyurl.

I should note that this probably isn’t the best way of doing things and it’s most certainly not the only way, but for a quick hack project on a Saturday afternoon, it fit the bill.

I forgot to mention that the inspiration for this post was Duncan Davidson’s post Everybody Wants Short Links.

Buildin' the Blog: Part 5 - Refactoring: Part 2

Saturday March 14, 2009 16:26 | comment icon 1 Comment

In my last Buildin’ the Blog article, I wrote about how I cleaned up my comments controller by moving all of the processing to the model. In this follow-up article, I’m going to write about how to access properties that aren’t part of your model object (aka table).

Take for example, a simple comments database table. It might look like this:

id full_name email_address url body

As you can see this is pretty straightforward, a single comment is comprised of a full_name, email_address, and the body. These attributes can easily be checked and processed in our comment model. Here comes the tricky part.

Take for instance my comment form below:

comment form photo

Name, email address, URL, and the body of the comment can all be mapped to database table fields. Unfortunately, Remember Me and Subscribe Via Email cannot and should not.

A beginner in Rails might write something like the following in their controller code:


if params[:subscribe]
#create a subscription record here
end

This code works but it leaves a lot of logic in the controller. The controller should be fairly lightweight, “I accept input from the user pass it to the model and then I pass it back to the browser/user.”

In order to get non-database bound fields to the model we use Ruby’s attr_accessor declaration (we could use attr_writer too to only write attributes and not read them).

For example:


class Comment < ActiveRecord::Base
  attr_accessor :subscribe
end

This allows me to create a form like the following:


  <% form_for @comment do |f| %>
  <%= f.text_field :full_name %>
  ...snip...
 <%= f.check_box :subscribe %>
 <%= f.submit %>

Once this is done, I can check what the value of the checkbox was set to in the model in a callback (let’s say either a before_save or an after_save):


  def before_save
    if self.subscribe == 1
      #create a subscription record here
    end
  end

It’s that simple. Now all of my logic can be done in the model.

With that out of the way, here is something to watch out for. Let’s say that you have a comments table that looks like this:

id full_name email_address url body is_admin

Obviously, the is_admin attribute should be set by the application and not by the user but unless you protect your model, the user can set any attribute he wants. Let’s say that you have a simple comments form with full_name, email_address, url, and body. The is_admin attribute is not displayed as a form field.

A malicious user could come by and change the form by adding the following or by submitting to the comment form using cURL. Here is an example:


  <input type="checkbox" name="comment[is_admin] checked="checked" />

By crafting this form and sending it, the user automatically becomes an admin!

One way to protect your application from this type of malicious activity is by protecting fields that should never be set by the user behind the attr_protected declaration. For example:


class Comment < ActiveRecord::Base
  attr_protected :is_admin
end

This will stop malicious users from trying to set attributes that should never be set by the user.

Buildin' the Blog: Part 5 - Refactoring

Sunday February 15, 2009 21:58 | comment icon 0 Comments

It’s been a long time since I posted something in this series, almost 3 years to be exact, and it’s about due.

One of the things that developers do when they are new to the MVC paradigm/Rails is to litter their controllers with all sorts of business rules code. This isn’t a fault really. For beginners it’s a way to get your app and running quickly.

As a developer matures with the MVC paradigm, they begin to see that there is a better way to do things (think Fat Model/Skinny Controller). That certainly was the case with me.

For instance, the create action of my blog’s comment controller (the heaviest action by far) weighed in at a hefty 61 lines of code. After doing a bit of refactoring, my controller has dropped to 25 lines of code. Still not perfect, but all of the comment processing code has been moved into the model.

Let’s take a look at how and why I made the changes.

First thing is first. Since I’m using the Akismet web service to check for comment spam, I need to track the referrer, the IP address of the client, and the User Agent.

I used to have a line of code in the create action that got this information by calling a method in the Application Controller.


options = get_browser_info

That method was defined as:


def get_browser_info
  options = { :ip_address => request.env["REMOTE_ADDR"], 
                :user_agent => request.env["HTTP_USER_AGENT"], :referer => request.env["HTTP_REFERER"] }
end

This worked, but it lacked a little sophistication.

The new method in the Application Controller:


def fetch_browser_info
 @browser_info = { :ip_address => request.env["REMOTE_ADDR"], 
  :user_agent => request.env["HTTP_USER_AGENT"], :referer => request.env["HTTP_REFERER"] }
end

Now in the Comments controller, I can run a before filter on the actions that need this:


before_filter :fetch_browser_info, :only => :create

Unfortunately, the old Akismet plugin that I was using, ror_akismet, enforced the use of extra methods in the controller. I changed this up, by copying the akismet.rb file to my lib directory and removing its dependence on the controller. And yes, I know that ror_akismet is the old library file and rakismet is the replacement. At the time, I didn’t want to install and futz with the new plugin.

That allowed me to pull this entire code block:


if is_spam?(:comment_content => @comment.body, :comment_author => @comment.name, 
                :comment_author_email => @comment.email, :user_ip => @comment.ip_address, 
                :referrer => @comment.referer, :user_agent => @comment.user_agent)

That now goes into the model. With a code block that looks like this:


if is_spam?( { :comment_content => self.body, :comment_author => self.name, :comment_author_email => self.email, :user_ip => self.ip_address, :referrer => self.referer, :user_agent => self.user_agent }.merge(self.akismet_attributes))

That’s it for this edition of Buildin’ the Blog, but I’m not done rebuilding my Comments create action. In the next part of the series, I’ll cover how to access variables that aren’t part of your Model’s attributes (table columns) and a quick note about security.

Object#type Errors with Single Table Inheritance

Tuesday February 03, 2009 23:09 | comment icon 0 Comments

Everybody probably already know this but what the hell. I was working on some code recently using Single Table Inheritance and was getting errors in the console and log when comparing the type field.

Before I get into the error itself and what I’m doing to correct it, a little background on Single Table Inheritance. Suppose you have employees in your database and you have two employee types; managers and staff.

You might have the following model objects:


class Manager < ActiveRecord::Base
end

class Staff < ActiveRecord::Base
end

And in the database, you’d have two separate tables; one for managers and one for staff. This is fine if the Manager table and the Staff table differ greatly from one another, but if they are identical with the exception of the type (Manager or Staff) then they can be combined in one table and be referenced in Rails using Single Table Inheritance.

This is done by having one class that Manager and Staff inherit from:


class Employee < ActiveRecord::Base
end

class Manager < Employee
end

class Staff < Employee
end

Now you can have one table, Employee, with a type column that differentiates that two. For example:

id type full_name phone_number
1 Staff Joe Jukem 5035551212
2 Manager Joe Blow 7025551212

Now here is where the problem comes in. Apparently “type” shouldn’t be used in your code. So when you’re doing something like this:


x = Employee.find :first
if x.type == Manager
   do something here
end

You’ll get a message that reads: warning: Object#type is deprecated; use Object#class instead. Now, obviously, the fix is to use something like this:


x = Employee.find :first
if x.class == Manager
   do something here
end

That works, but I like the more readable version using the is_a? method. For example:


x = Employee.find :first
if x.is_a?(Manager)
   do something here
end

Blasting off on a Rocket Ship

Sunday December 07, 2008 23:16 | comment icon 2 Comments

It’s often said (and I wish that I could remember the exact quote) that in order to climb a mountain, you have to take 1000 individual steps. Over the past few years, I’ve been trying to climb over a mountain of my own; my attempted transition from working as a sysadmin to working with code as a web developer.

It’s been a long, arduous path with many days and nights sitting in front of my Mac trying to learn the ins and outs of a very fast moving target. There were times that I didn’t think that I would ever achieve my goals but there is a light at the end of every tunnel.

6 weeks ago, my hard work and determination finally paid off when I accepted a full time developer position at Planet Argon in the heart of Portland, Oregon.

I still can’t believe that I get to work on a Mac with my preferred web framework and programming language. Of course, these are just tools and even in the wrong environment the best tools won’t help you or make you happy. Luckily for me, the environment couldn’t be better. I work alongside a group of talented and funny individuals that make work seem…well not so much like work. I know, it’s cliche, but it’s true.

Rolled Out Gravatars

Wednesday September 03, 2008 21:46 | comment icon 1 Comment

One of the things that I’ve had in mind when I started coding this blog in Rails was to eventually support Gravatars otherwise known as Globally Recognized Avatars.

Before rolling out this feature, comments had a little astronaut next to the speech bubble for each and every individual comment. If you have registered your email and uploaded a photo with the Gravatar service, it will no longer display the astronaut icon and it will load the registered image. If you haven’t registered, your comment gets a default kanji image.

Making this change in Rails was actually pretty trivial especially since Michael Mayo posted a very nice tutorial not long ago on his blog.

I did make some modifications from the code that he posted.

One of the more prominent changes that I made was to split out the image creation from the just generating the URL.

For example, I have this first method in my application_helper.rb file:


def gravatar_url_for(email, options = {})
      url_for({ :gravatar_id => Digest.MD5.hexdigest(email.downcase), :host => 'www.gravatar.com',
                   :protocol => 'http://', :only_path => false, :controller => 'avatar.php',
                   :default => 'http://eddorre.com/images/visitor.png',
                   :rating => 'G'}.merge(options))
end

I convert the email address to lowercase letters with the downcase method because an MD5 of noemail@eddorre.com and NOEMAIL@eddorre.com are actually two different things. This way, there can be no error. One of the other settings that I’m passing in is a “default” flag. If you haven’t registered with the Gravatar service, I’ll just use the astronaut image that I have and finally I don’t want goatse photos or worse showing up on my blog so I make the rating a mandatory “G”.

Notice that the above method doesn’t actually generate an image tag, it will only generate a URL.

For that, I have a second helper method defined simply as:


def gravatar_image(email, options = {})
      image_tag(gravatar_url_for(email, options), :alt => "Author Image")
end

This is the code that actually creates the Gravatar image.

Now in my view code, I can do the following (where @comment.email represents a variable with the user’s email address):


<%= gravatar_image(@comment.email, { :size => 40 }) %>

And it will display the image correctly. I should note that Michael’s example lists a size in height and width and you’ll notice that I’m passing the size as just an integer. I believe that the height and width options have been deprecated in favor of the more succinct size option.

Site Updates

Thursday August 28, 2008 23:55 | comment icon 0 Comments

Over the past few days, I fell in love with updating my blog engine again. I go through these cycles where after an update, I won’t touch it for a while. Then something comes along that I need to fix and I’ll update a whole bunch of stuff all at once.

This time I went in and added some new features, updates old pages, and fixed some bugs. One of the pages that had been published, but was not publicly accessible, is the changelog. A changelog is a simple log of changes that have occurred during a project that includes new features and bug fixes. This is the first time that it’s been publicly linked. I’ll keep updating this as I add features and continue doing bug fixes.

You can access the changelog from the updated About page which contains updated information about the blog URL name (eddorre) as well as information about the tools that I use. Someday there will be information about me but I haven’t figured out if I’m going to write (hard to write about yourself) or have someone that I know do it.

As my changelog mentions, I’ve added Twitter updates. This just simply lists out the last 5 updates that I’ve made in Twitter via a JSON call. If you’re curious there are full updates available.

I’ve also fixed a nasty bug (that I thought that I had fixed before) where the order of the comments were listed in the wrong order (latest comment first in the list instead of last).

All of those changes are visible to everyone but there are changes that aren’t available for everyone to see. The mostly involve the back end publishing part of the site. Those updates include shoring my Models by using Rails’ new named_scope options as well as including several helper methods here and there.

I’m proud of what I’ve accomplished considering that I work on this in my spare time.

Calorie Counter Application

Thursday April 03, 2008 00:30 | comment icon 7 Comments

Calorie Counter ApplicationDear GF and I have iPhones and she’s become increasingly addicted to the fact that she can access web applications online at any time (as long as she has at least EDGE access).

A couple of weeks ago, she was looking online for a calorie counting web application and she was frustrated by the fact that she couldn’t find something she liked. Since I have mad Google-Fu skills, she asked me to try to find something. Instead, I asked her what her requirements were and since they were simple enough, I offered to write an iPhone specific application for her in Ruby on Rails.

Even though the application is dead simple, I learned a lot this time around since I tried to follow the recommended practices defined by the Rails community from coding to deployment. I’ve still got some more to learn (does one ever stop learning? Maybe when you’re dead), but I’m becoming more and more confident in my Rails skills.

She’s been testing the application on my staging server for the last week and we’ve discovered some bugs that were pretty egregious. Now that I have those worked out, I’ve deployed the beta application at caloriecounter.eddorre.com.

Although the application was written specifically to be displayed on the iPhone, I’ve tested it using desktop browsers such as Firefox, Safari, and Internet Explorer 7 (IE 6 is dead to me – I won’t even test against it). With the exception of a CSS styling bug in IE 7, it’ll work just fine on your desktop.

In addition to to all of this, I’ve actually allowed open registration to the application so that anyone can use it. I’m actually quite nervous about this as no one has ever used my web software besides me. Apparently, it might get more use than I expected since Dear GF’s work is having some sort of Biggest Loser-esque challenge at work and several of her co-workers have expressed interest in using it.

One more thing, at this time, I’m hosting the application on my home server. If you decide to take it for a spin, please be patient with the poor box.

Removing Old Rails Session Files

Sunday September 23, 2007 18:29 | comment icon 0 Comments

I’m sure that this is elementary for all of the *nix experts out there but I recently discovered this and thought that I would share. Ruby on Rails, by default, holds session information on disk in [application root]/tmp/sessions/ and unfortunately they aren’t purged automatically. Even for small sites, the number if session files can quickly grow out of control. For large sites, it can bring an application server to its knees by filling up the disk.

The “best practice” for Rails sites is to use the database to keep track of sessions using following commands:

  • ruby script/generate session_migration
  • rake db:migrate

Then uncomment the line in the environment.rb file that reads: config.action_controller.session_store = :active_record_store

If you’ve completed the above steps, then your sessions should now be stored in the database but that doesn’t remove the session files from disk. If you’ve been running with sessions on disk for a while, the command, rm /[application root/tmp/sessions/ruby_sess.* will fail with the error “Argument list too long”. If this happens, you can delete the files by running the following command:

find /[application root]/tmp/sessions/ -name ‘ruby_sess.*’ | xargs rm

I found this little gem of information at ducea.com. The comments have other commands that you can run to delete mass files if necessary.

Akismet Ruby on Rails Plugin

Tuesday July 10, 2007 01:16 | comment icon 0 Comments

I’m re-doing my blog engine. I’m focusing on refactoring old crufty code as well as expanding my knowledge of Ruby on Rails.

So far everything is on track and I should be done with it soon. One of the things that I wanted to focus on was the use of modules and plugins. Last time, I was using my own code for accessing the Akismet web service. This time around, I downloaded the ror-akismet plugin and I’m extending my comments class using the built in downloaded methods.

However there seemed to be a bug in the works. Every time that I included the declaration “include Akismet” into my comments controller, all of the other methods would break.

I started tearing out bits of my code and then the modules’ code and no matter what I did, everything would go to hell when I added the include declaration.

It turns out that Rails (1.2.3) seemed to be freaking out because the plugin directory that was downloaded was called ror-akismet.

Once I changed it to ror_akismet, everything worked fine.

Ruby and Ruby on Rails Books

Wednesday September 06, 2006 20:37 | comment icon 0 Comments

The Unofficial Ruby on Rails blog has a list of 8 upcoming Ruby on Rails books. It’s a good list but unfortunately the list is incomplete.

I’ve compiled a list of all the Ruby and Ruby on Rails books that I know of. If there is a second edition of a version of the way, I’ll only list that in the upcoming section (with the exception of the book co-authored by DHH). There is no need to get books that are on their way out.

NOTE: None of the links below are Amazon affiliate links.

Ruby – Released

Ruby – Upcoming

Ruby on Rails – Released

Ruby on Rails – Upcoming

These are all of the ones that I know. If you think that I’ve missed some, let me know and I’ll add it to the list.

Rails' Growing Pains

Thursday August 31, 2006 03:07 | comment icon 0 Comments

Kevin Clark recently wrote an article titled Guide: Things You Shouldn’t Be Doing in Rails.  As the title suggests, the article outlines code that shouldn’t be used in Ruby on Rails applications.

The article was well intentioned and written a bit tongue-in-cheek but it sparked quite a debate in the comments. While I’m glad that Kevin pointed out some bad coding behavior, I think the article may have aroused such strong emotion because, for the most part, he didn’t list alternatives to the bad behavior.

For example; he advises that people should not to access instance variables that they didn’t create but he doesn’t give an example of how to fix this. This is going to light the fire under some people; especially people that are trying to learn this stuff for the first time.

An underlying theme in the comments has been the frustration with out of date and deprecated information all across the board. Even “The Book” (Agile Web Development with Rails: A Pragmatic Guide) will lead you astray with crufty code.

Obviously Rails is going through some growing pains and accurate documentation and tutorials are in heavy demand.

As a relative newcomer to Rails, I understand frustration with poor documentation quite well. If “The Book” is wrong, what’s the alternative?

Well, right now there aren’t many books available for Ruby on Rails. but I’ve managed to compile a list.

Here’s a list of published books and e-books that might help newcomers on their way.

If I missed one that you know of, let me know and I’ll be glad to throw it in the list.

More books are coming but the majority of them won’t hit the shelves until November or December of this year.

Update: Nuby on Rails, lists all of the deprecated code that shouldn’t be used in a new plugin. It’s good to know.

RailsConf2007

Thursday July 13, 2006 00:54 | comment icon 0 Comments

I wasn’t able to go to RailsConf2006 primarily because it was in Chicago but I can imagine that I’m going next year.

I’m listening to David Heinemeier Hansson’s keynote and at the beginning, they announced that the next RailsConf will be held in Portland, OR (May 17th-20th – at the convention center).

Ruby on Rails - From Start to Finish

Wednesday June 14, 2006 22:16 | comment icon 0 Comments

When I first started with the notion of doing Ruby on Rails, I had it in my head that I wanted to do it the “right” way. The “right” way, in my head, was to use it on the platform that it was written for; Linux.

I’ve always been a Windows guy, but I’ve never shied away from a challenge, so I took the bull by the horns and sat down to write a Ruby on Rails app. I got gored…and trampled…and mauled…and, well you get the idea.

Call me a sissy, but I was used to point and click installers. So, something that I thought would be easy wound up being significantly more difficult that I had expected.

I guess I underestimated it, after all, I had to learn everything from scratch; the operating system (although I’ve had some UNIX training in the past), the database, the web server, the programming language, and finally the web application framework.

I wanted to compile a set of notes for myself for when I have to do it again, so I wrote up some steps to get Ruby on Rails installed on Debian Sarge with a MySQL database, Lighttpd. This includes integration with the version control software, Subversion and walks through how to create a database and a simple lighttpd.conf file.

It should really detail the deployment application Capistrano, but I wanted to do the stuff hands on before learning a system with a level of abstraction. Maybe I’ll write up those notes when I get there.

The notes are just a simple text file and I’m always amenable to updating it in case I’m doing something horribly inefficient. Hopefully, they’ll save a newbie some time and anguish.

Buildin' the Blog: Part 2 - Installing Ruby on Rails

Tuesday January 31, 2006 01:43 | comment icon 6 Comments

Part 1 of this series is here.

I originally was going to have this part come later in this series, but I wanted to install Ruby on Rails a bit before I started writing my blog application so that I could become more familiar with the programming language and the web framework. Add to that, the fact that I installed it last night makes it fresh in my head.

I picked Kubuntu to be my development platform for a few reasons. I’d really like to use a Mac along with TextMate, but I don’t have the capital for a new Mac. Oh sweet, MacBook, I will have you one day…

But I digress, it’s probably best to use Kubuntu at first anyway. One of the reasons why I chose this distribution of Linux is because, well, I wanted to learn Linux. I chose this specific distribution because I plan on using Debian as my production platform and since Kubuntu is based on Debian it seemed to make sense. I should note that I don’t use Ubuntu because it comes with the terrible GUI, GNOME (although I’m perfectly aware that I can switch to KDE using Ubuntu, I just wanted it all in one package).

Anyway, it’s time to get to the good stuff.

With modern Linux distributions, you can install software using a package manager and Kubuntu (and Debian) is no different. I could have easily downloaded Ruby with the apt program and then installed Rails on top of it but the latest version avaliable to the apt program is Ruby 1.8.3 while the latest version of Ruby is 1.8.4. I should note that Ruby 1.8.3 is not recommended for use with Rails.

So I had two choices, install an old (and incompatible) version with apt or install from source.

I decided on installing from source. First thing is first, I gotta install Firefox in order to browse the web (I don’t really like Konqueror – the web browser that comes with KDE) and download the source.

I run this command to get Firefox:

sudo apt-get install firefox

This installs Firefox 1.0.7 and displays a warning message when loading, but that’s fine for now – it’s not critical. It’s time to get Ruby and then Rails. The Ruby on Rails site has very simplistic instructions on how to install both Ruby and Rails. They are deceptively simple and as I’ve found with all things Linux, it’s actually much harder than adverstised.

I created a directory in /home/carlos called work where I could download packages and compile the programs. I download both Ruby 1.8.4 and Ruby gems into these folders.

You have to install Ruby first, so I run this command in the directory where I’ve download Ruby:

tar xvf ruby-1.8.4.tar.gz

This creates a directory called ruby-1.8.4. Moving into that directory, I attempt to run this command:

./configure

And it gives and error stating that “no acceptable C compile was found in $PATH.”

I guess I have to install a C compiler so I run this command:

sudo apt-get install gcc

It does its thing and I try the ./configure command again. This time it’s another error. C compiler cannot create executables. Hrrm, it’s turning out that it’s not as easy as “download and go” after all.

After doing some Google searches, I found out that I need to install some development packages first, so I run the following commands (the second command is used for later when attempting to get RubyGems working):

sudo apt-get install libc6-dev
sudo apt-get install zlib1g-dev


BAM. That got it working. It does it’s thing and makes a make file. I go to make the…uh…make file and when typing in the command “make”, I get the error: bash: make: command not found. Unbelievable. I then run the following commands (which run without error):

sudo apt-get install make
make
sudo make install

I’m not sure why a base install of Kubuntu doesn’t have gcc, make, libc6-dev, and zlib1g-dev but I’ll leave that to smarter people to figure out.

I first have to unpack Ruby Gems. The command (to be run where I downloaded Ruby Gems) is

tar -xvf rubygems-0.8.11.tgz

That creates a rubygems-0.8.11 directory. The following commands are to be run in that directory:

sudo ruby setup.rb
gem install rails —include-dependencies

Note if you get an error here that reads: The error is no such file to load - zlib (LoadError), it means that you have to install zlib1g-dev first. Unfortunately you also have to go back and run the .configure, make, make install commands in the Ruby directory again.

In theory, Ruby and Rails should now be installed. Let’s test it out by running the commands:

rails /home/carlos/work/test
cd /home/carlos/work/test
ruby script/server

You should see WEBrick 1.3.1 startup and at this time, I’m satisfied that Ruby on Rails has successfully been installed.

All in all, it was way more complicated than it needed to be and if I wasn’t so determined to get it working I would have quit and just double-clicked the installer for Visual Studio.NET 2005.

Buildin' the Blog: Preface

Monday January 23, 2006 17:02 | comment icon 0 Comments

I’ve been working on updating this site to what I call “version 3” for a while. “Version 3” has been set to include a whole new look and design as well as some programming additions to make it…well, better.

At first I was committed to using ASP.NET as my programming platform of choice (this site currently runs under ASP.NET 1.1), but somewhere along the line, I lost enthusiasm for using it.

Along the way, I’ve discovered Ruby on Rails and I’ve become determined to use it for the new site. Unfortunately, using Ruby on Rails on the preferred platform (Linux or Mac OS X) makes the learning curve quite steep.

As I thought more and more about what I’ve learned and what I’ve still yet to learn, I decided to make a set of articles that went from the first step of building a blog to the final steps of deployment and rolling it out live.

It’s helpful for me to document my progress and it might be helpful for other people out there as well.

Some people might say that I’m re-inventing the wheel considering the amount of great blogging packages out there (Typo, Das Blog, .Text, Wordpress, Movable Type, etc). I don’t see it like that at all. Since my goal is to learn Ruby on Rails on an Open Source platform, I see as “figuring out how the wheel works; by itself and in conjunction with other systems.”

The technologies that I’m going to be using will help me build my skills by learning basic skills in Ruby on Rails like CRUD (Create, Retrieve, Update and Delete), as well as more advanced skills like XML-RPC and AJAX.

Hopefully, whoever reads these can pull something useful out of them.

Next up: Buildin’ the Blog: Part 1 – Design Web Standards and Design Inspiration.

Linux Books

Saturday December 10, 2005 19:21 | comment icon 3 Comments

Work is still continuing on migrating this site from ASP.NET to Ruby on Rails. The reasons why aren’t really the basis for this post, so I’ll exclude them from it.

The majority of Ruby on Rails sites run on Linux or a form of UNIX, so I figured that I would take the plunge and do so as well. I consider myself to be a pretty accomplished Windows administrator, but in the realm of Linux, I’m but a wee young lad.

With that in mind, I’m browsing Amazon.com to see if there are any books that might help to soothe the learning pains.

In addition to learning Linux (the right way), I’m also interested in learning Linux web servers the right way as well. Probably the most popular web server for Linux is the Apache server, but I know that LightTPD is starting to gain ground especially amongst Ruby on Rails developers.

Imagine my surprise when I couldn’t find any books on LightTPD. Now, I know that this is a fairly new web server, but I’m used to technical books being written on alpha and beta releases, so it was quite a surprise.

Too bad I don’t know more about it or I would write my own. I think it would sell like hotcakes (if written right).

Penny Arcade on RoR

Monday November 14, 2005 15:26 | comment icon 0 Comments

Penny Arcade has re-done their website. At first, I thought I hit the wrong site or something, but it’s growing on me. According to Gabe, the new version of Penny Arcade runs on Ruby on Rails.

Instead of me talking about it, it’s best just to quote his own words:

Penny Arcade right now represents one of the largest implementations of “rails” on the intertron. I went and looked at a website about rails and then I got a headache. From what I gathered its either some kind of cutting edge programming language, or a way to liquefy a mans brain inside his skull. I’m told that it means the site looks better and loads faster regardless of whatever hippy web browser you decide to use. Fuck M$!

Tutorials for Ruby on Rails

Tuesday October 25, 2005 22:52 | comment icon 0 Comments

After you’ve installed Ruby on Rails, you want to know what you’re doing. I strongly suggest that you purchase Programming Ruby: The Pragmatic Programmers’ Guide, Second Edition and Agile Web Development with Rails, but there are online tutorials that will get your started in case you don’t have those books.

View or read them in this order:

Finally, here are some good links that might help you on your new endeavor.

Follies Installing Linux and Ruby on Rails

Tuesday October 25, 2005 22:39 | comment icon 1 Comment

This past Saturday, I was determined to get Ruby on Rails
installed…in Linux. I could have gone the easy route and installed in
Windows, but I wanted…well I want to branch out from the standard
Windows world that I know.

It turned out to be a 12 hour exercise in frustration. All I can say
is, thank god for VMware. Without it, I would have lost my sanity.

I first started my little exercise with OpenSuse10. It’s a brand new
free version of Suse…and looking back with hindsight, I’ve come to
the conclusion that it might be too much on the bleeding edge.

Whenever I tried to compile Ruby, it would give me an error. Everytime
that I thought I was getting closer to the solution, it would blow up
in a different fashion. So I deleted the virtual disk (the virtual
equivalent of tearing your hard drive out of your machine and flinging
it off a 10 story balcony) so I tried one of the other Linux
distributions that I had downloaded; Kubuntu (the KDE version of
Ubuntu). I’ve used quite a few distributions of Linux over the years
(and have always come back to Windows), but this one has to be one of
the worst ever.

The install of Kubuntu was fairly easy. Too easy. Not only did it not
ask me for a root password, it didn’t ask me to create a user. I went
to create a directory on /var/tmp and naturally you have to use the
root account to do (sudo mkdir /var/tmp/carlos). When it asked for a
password I was flabbergasted. I didn’t give it one. I tried a null
password and the word password. When it didn’t take the second one, I
shut off the virtual machine and deleted the virtual disk. Time to
install another distribution. This time I tried Fedora Core 4.

I had to reinstall it twice because I’m such a newbie, but on the
second time I was able to download Ruby and Rails and succesfully
install them.

If I can recommend one thing for the Ruby and Ruby on Rails community,
it would be to make the install easier. If you think I’m out of my
mind, read this blog entry.
If that doesn’t make you frustrated with the install then nothing will.
His documentation is one of the reasons that I stuck through what I
did. I knew that there was a light at the end of the tunnel, even for a
Linux newbie like me.

I hope that your install goes better than mine, but here is what I did:

This is unrelated, but I thought that I would post it here. When you
install Suse10, Fedora Core 4, and any other OS into a virtual machine,
it’ll complain that the VMware tools are missing. Installing from the
RPM does nothing. You actually have to do this:


  1. On the VMware window itself, click on VM and select Install
    VMware tools. This should automatically mount the DVD to
    /media/<name of device>. In my case, it was in my DVD burner so
    the entire path was /media/dvdrecorder.

  2. I copy the tar.gz file to that temp directory (although I found
    out that the location of that temp directory might not be a good idea,
    but that’s a tale for another post). Using this command (at this point
    I’m su’d as root which is this command: su root) mv
    /home/carlos/Desktop /var/tmp/carlos/.

  3. Then I unpack the files using tar -xzf  /var/tmp/carlos/<name of file>

  4. And then finally I change into the newly unpacked directory cd
    /var/tmp/carlos/<name of new directory> and run a
    ./vmware-install.pl.

  5. Answer all of the questions and then choose my resolution.
    Unfortunately, to take effect, you’ll have to reboot and that command
    is, well, reboot. Finally I can see virtual machine at 1024*768.

Installing Ruby:
Note: During both installs, I had su’d to root. Command is su root.


  1. Download the latest verison of Ruby (at the time of this writing it’s 1.8.3).

  2. Move the tar.gz file to the tmp directory or your could unpack it
    there. The command that I used was mv /home/carlos/Desktop/<name of
    file> /var/tmp/carlos/.
  3. Unpack it: tar-xzf <name of file>.
  4. Change into the newly created directory: cd /var/tmp/carlos/<newly created directory>.
  5. Run this command: ./configure.
  6. Run this command: make.
  7. Run this command: make install.
  8. If the gods have smiled upon you, then Ruby has been installed.

Installing Rails:


  1. Download the latest version of Rubygems. At the time of this writing it’s 0.8.11.

  2. Move the .tgz file to the tmp directory. The command is: mv. /home/carlos/Desktop/<name of file> /var/tmp/carlos/.

  3. Unpack it: tar -xvf /var/tmp/carlos/<name of file>.

  4. Change into the newly created directory and run the command ruby
    setup.rb. NOTE: This is where it would fail to install on OpenSuse10. I
    could never get past that point with that OS.

  5. Run the command gem install rails —include-dependencies.

  6. If the gods have smiled upon you, then Rails has been installed.

Have a beer, you earned it.

end kanji