eddorre

My Web Development Toolbox

November 01, 2009 — 3 Comments

I recently posted a guide to installing Ruby on Rails on a Mac that was adapted from my own installation notes. The article was specifically focused (and rightfully so) on just installing Ruby on Rails but I wanted to cover some of the apps that fill out my web development toolbox after a fresh install.

LaunchBar

LaunchBar

Not necessarily directly related to web development, but I find that I can’t live without a quick application launcher anymore. Instead of digging through the Applications directory for the app that I want to run or littering my dock with icons, I just hit CTRL + SPACE type in the first few letters of the application and hit ENTER when LaunchBar finds it.

LaunchBar isn’t free, but it’s what I’ve been using for a while.

Other alternatives: Quicksilver, Google’s Quick Search Box

TextMate

textmate

TextMate is where I spend a majority of my day. This text editor does it all. Ruby, Rails, Javascript, HTML, CSS, C, Objective-C and more. Beyond the huge number of languages that it supports (all with theme-able color coded syntax) it has a ton of bundles that provide keyboard shortcuts that dramatically speed up your development time.

Other alternatives: BBEdit, Coda

Safari’s Web Inspector and Firefox’s Firebug

Web Inspector

Firebug

One of the first things that I do when setting up a new Mac, is I turn on the Web Inspector in Safari and install Firebug in Firefox. I don’t think that I could develop on the web without these tools. Inspecting elements, the Javascript console, integrated resource tracking, Javascript profiling and a whole lot more.

Although I started out using Firebug exclusively, I’ve found that I actually prefer the Web Inspector now and it’s about to get even better. Joseph “BogoJoker” Pecoraro put up an excellent post titled Improving the Web Inspector with a ton of forthcoming improvements to the Web Inspector. If you’re impatient and want to play with these features now, you can download the WebKit Nightly builds.

Skitch

Skitch

An immensely valuable tool for collaboration. With it, you can take a snapshot of anything on your screen and then annotate it with text and shapes (of any color). You can then upload those images to Skitch’s web service and share among co-workers and clients. Did I mention that it’s free?

All of the image from this post were taken with Skitch.

Alternative: LittleSnapper

xScope

Screen Loupe

Iconfactory’s xScope is 7 tools in one. Dimensions, Rulers, Screens, Loupe, Guides, Frames, and Crosshair. Basically, xScope is a set of tools that are ideal for measuring , aligning and inspecting on screen graphics, elements, and layout. All of the tools float above windows and UI elements, so they don’t get in your way.

I find that the Loupe (pictured above) tool is my favorite and most used out of all of them. It magnifies anything that’s underneath it and gives you the X and Y coordinates as well as color information in hex, RGB, and HSB.

Color Picker

Color Picker

Speaking of color, OS X’s built in Color Picker the tool for building a color palette. Unfortunately, by default the Color Picker app is only available in applications where you can modify the color or fonts or graphics. Luckily, there is a way to make the Color Picker its own app by just one line of Applescript code. The instructions are easy:

  • Open the AppleScript Editor
  • Type the words: choose color
  • Save the file as an application giving it the title of Color Picker (this can be whatever you want but it makes sense to just call it Color Picker, no?)

You can replace the default script icon with an icon of your choice by doing the following:

  • Right click on the Color Picker application and selecting Show Package Contents
  • Open the Contents/Resources directory
  • Replace the applet.icns file with one of your choice

You can download the one that I use:

Color Picker Icon

Copy the newly created application to your Applications folder and now you can launch the Color Picker from anywhere.

If that wasn’t enough you can extend the Color Picker itself. Installing extensions is as easy as copying the extension file to ~/Library/ColorPickers or alternatively ~/Users/[username]/Library/ColorPickers if you only want the extensions to be available for a specific user.

I’m currently using 3 extensions to the Color Picker. The first one is the Developer Color Picker from Panic. This extension allows you to copy color is a variety of formats to the clipboard; NSColor, CGColorRef, UIColor, HTML (aka hex), and CSS (aka RGB).

The second extension, is the Hex Color Picker from Waffle Software. This is useful if you don’t want all of the options that Panic’s Developer Color Picker gives you. Just the hex, please.

The third extension that I have installed is Mondrainum 2 from the folks and Lithoglyph. Mondranium uses an API to talk to the Adobe Kuler web service. What is Adobe Kuler? It’s a site that allows one to create and share color themes.

Mondranium

Want a color theme for your site but you’re stuck or are low on inspiration? Choose from over 14,000 color palettes (as of this writing) all from the Color Picker itself.

Certainly these are not all of the tools that I use but these are the ones that I keep coming back to day after day and developing on the web wouldn’t be as much fun without these tools.

What tools do you use on a day to day basis?

Tutorial: Filtering results with jQuery UI Slider and Rails

November 05, 2009 — 22 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. The tutorial also uses jQuery 1.3.2 and jQuery UI 1.7.2 (the jQuery files can be downloaded from the Github repository.

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 as well as RSpec and RSpec Rails.

sudo gem install jrails
sudo gem install faker
sudo gem install rspec
sudo gem install rspec-rails

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

  config.gem "faker"
  config.gem "jrails", :lib => false

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
      
    end

      add_index :stocks, :price
  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.