Thursday, May 26, 2011

A Location-based small business reviewing site

Here's a link to what I think is a refreshing, positive, alternative to Yelp. It allows one to recommend business they like to their friends. No whining or hostility necessary. I had a chance to chat a bit with Jim Delli Santi, Likelist's founder, at Web 2.0 and really liked his vision. I'm looking forward to seeing them grow.

Build Your First Ruby on Rails App in Minutes!

Building your first app in Rails 3 is pretty simple and if you've got your git account, a heroku account and all the components installed and know your way around UNIX, you can have one up and running in just minutes.

Go to your terminal and enter the following:

rails new demo_app

You should get in return about 75 lines of text that look something like this:
      create  README
      create  Rakefile
      create  .gitignore
      create  Gemfile
      create  app
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/mailers
      create  app/models
      create  app/views/layouts/application.html.erb
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/secret_token.rb
      create  config/initializers/session_store.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  doc
      create  doc/README_FOR_APP
      create  lib
      create  lib/tasks
      create  lib/tasks/.gitkeep
      create  log
      create  log/server.log
      create  log/production.log
      create  log/development.log
      create  log/test.log
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/favicon.ico
      create  public/index.html
      create  public/robots.txt
      create  public/images
      create  public/images/rails.png
      create  public/stylesheets
      create  public/stylesheets/.gitkeep
      create  public/javascripts
      create  public/javascripts/application.js
      create  public/javascripts/controls.js
      create  public/javascripts/dragdrop.js
      create  public/javascripts/effects.js
      create  public/javascripts/prototype.js
      create  public/javascripts/rails.js
      create  script
      create  script/rails
      create  test
      create  test/fixtures
      create  test/functional
      create  test/integration
      create  test/performance/browsing_test.rb
      create  test/test_helper.rb
      create  test/unit
      create  tmp
      create  tmp/sessions
      create  tmp/sockets
      create  tmp/cache
      create  tmp/pids
      create  vendor/plugins
      create  vendor/plugins/.gitkeep

Move into the demo_app directory and run bundler.

cd demo_app

What you get in return should look something like this:
Fetching source index for
Installing rake (0.9.0)
Using abstract (1.0.0)
Using activesupport (3.0.7)
Using builder (2.1.2)
Using i18n (0.5.0)
Using activemodel (3.0.7)
Using erubis (2.6.6)
Installing rack (1.2.3)
Using rack-mount (0.6.14)
Using rack-test (0.5.7)
Using tzinfo (0.3.27)
Using actionpack (3.0.7)
Using mime-types (1.16)
Using polyglot (0.3.1)
Using treetop (1.4.9)
Using mail (2.2.19)
Using actionmailer (3.0.7)
Installing arel (2.0.10)
Using activerecord (3.0.7)
Using activeresource (3.0.7)
Using bundler (1.0.10)
Using thor (0.14.6)
Using railties (3.0.7)
Using rails (3.0.7)
Using sqlite3 (1.3.3)
Your bundle is complete! It was installed into /Users/maryjenn/.rvm/gems/ruby-1.9.2-p0

Start your rails server using rails server . Then, open your browser to http://localhost:3000/. You should see the default Rails Welcome page. It looks like this:

Next, let's add your app to your git repository. Use ctrl + c to stop your server. Type the following in your terminal:
git init This initializes your git repository.
git add . This adds the app to your repository.
git commit -m "new app" This commits the app to your repository. The "-m" allows you to add a note about what is in the commit. This is especially useful when you are collaborating on a project with others and need to communicate what changes you made.

Next, let's get it on the web! We'll push it to Heroku. First, create a Heroku repository:

heroku create

You'll get a nice URL like this: If you go to the URL, you'll see a sort of placeholder for your app, but you won't see what you see on your local server because we haven't added it yet. Let's do that.

git push heroku master

You should then see something that looks like this in your terminal:

Counting objects: 63, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (48/48), done.
Writing objects: 100% (63/63), 86.11 KiB, done.
Total 63 (delta 2), reused 0 (delta 0)

-----> Heroku receiving push
-----> Rails app detected
-----> Detected Rails is not set to serve static_assets
       Installing rails3_serve_static_assets... done
-----> Configure Rails 3 to disable x-sendfile
       Installing rails3_disable_x_sendfile... done
-----> Configure Rails to log to stdout
       Installing rails_log_stdout... done
-----> Gemfile detected, running Bundler version 1.0.7
       Unresolved dependencies detected; Installing...
       Using --without development:test
       Fetching source index for
       Installing rake (0.9.0)
       Installing abstract (1.0.0)
       Installing activesupport (3.0.7)
       Installing builder (2.1.2)
       Installing i18n (0.5.0)
       Installing activemodel (3.0.7)
       Installing erubis (2.6.6)
       Installing rack (1.2.3)
       Installing rack-mount (0.6.14)
       Installing rack-test (0.5.7)
       Installing tzinfo (0.3.27)
       Installing actionpack (3.0.7)
       Installing mime-types (1.16)
       Installing polyglot (0.3.1)
       Installing treetop (1.4.9)
       Installing mail (2.2.19)
       Installing actionmailer (3.0.7)
       Installing arel (2.0.10)
       Installing activerecord (3.0.7)
       Installing activeresource (3.0.7)
       Using bundler (1.0.7)
       Installing thor (0.14.6)
       Installing railties (3.0.7)
       Installing rails (3.0.7)
       Installing sqlite3 (1.3.3) with native extensions
       Your bundle is complete! It was installed into ./.bundle/gems/
-----> Compiled slug size is 3.8MB
-----> Launching... done, v4 deployed to Heroku

 * [new branch]      master -> master

Go to the URL Heroku created for you, and you should see your default Rails app! See? Easy!

Next, let's do some editing of the files rails generated to build some simple functionality into the app we created by creating a list. Let's do a song list--we'll list them by title and artist. We'll use Rails' scaffolding feature for this exercise, but in a professional context, it is not often used because it generates a lot of extra files that may or may not be used.

rails generate scaffold song title:string artist:string

In your terminal, you should see this:
         invoke  active_record
      create    db/migrate/20110525191620_create_songs.rb
      create    app/models/song.rb
      invoke    test_unit
      create      test/unit/song_test.rb
      create      test/fixtures/songs.yml
       route  resources :songs
      invoke  scaffold_controller
      create    app/controllers/songs_controller.rb
      invoke    erb
      create      app/views/songs
      create      app/views/songs/index.html.erb
      create      app/views/songs/edit.html.erb
      create      app/views/songs/show.html.erb
      create      app/views/songs/new.html.erb
      create      app/views/songs/_form.html.erb
      invoke    test_unit
      create      test/functional/songs_controller_test.rb
      invoke    helper
      create      app/helpers/songs_helper.rb
      invoke      test_unit
      create        test/unit/helpers/songs_helper_test.rb
      invoke  stylesheets
      create    public/stylesheets/scaffold.css

Let's do a migration: rake db:migrate

You'll see that rake has built a table for your songs!

(in /Users/maryjenn/src/demo_app)
==  CreateSongs: migrating ====================================================
-- create_table(:songs)
   -> 0.0018s
==  CreateSongs: migrated (0.0019s) ===========================================

Let's start the rails server again and go to localhost:3000 in your browser. You'll still see the rails default welcome page.

What? Why is that? Well, I'll talk about that in a minute and show you how to fix it, but add "/songs" to your URL. You should see a page with a header "Listing songs". Woohoo! We've actually built something! Now, play around with it. Notice there is a link to add new songs. C'mon, just add a couple.

Now, let's go look at the terminal. Notice that there is something going on under the hood, so to speak:

Parameters: {"utf8"=>"?", "authenticity_token"=>"oJP1EQL/KyGiswURylv9ySUVaWkjfwkAOge5GLI+8R0=", "song"=>{"title"=>"Go Do", "artist"=>"Jonsi"}, "commit"=>"Create Song"}
  [b]AREL (0.5ms) [/b] INSERT INTO "songs" ("title", "artist", "created_at", "updated_at") VALUES ('Go Do', 'Jonsi', '2011-05-26 15:19:40.314160', '2011-05-26 15:19:40.314160')

This is Active Record adding your entries to your app's data table. To me, Active Record is really where all the RoR magic happens. I'll get into Active Record in my next code sample, so be sure to check that one out. For now, let's change the routes so that the URL goes directly to our app, then deploy it to Heroku.

To redirect the URL, first go to /public/index.html and change name of that file to something like "old_index.html". If you don't do this, the browser will pick this up no matter what else you do. It's the default index page.

Then, go to /config/routes.rb and find the line that reads #root :to => "welcome#index". Uncomment it and change it to root :to => "songs#index". Save it.

Ctrl+C and Restart your server, then reload localhost:3000 in your browser. You should see your app, with the entries you have already made!

Now let's push it and deploy it.  
git add .
git commit -m "did migration and changed route" 
git push heroku master 
heroku rake db:migrate This adds your data table to your deployed app. Don't forget this!

Go check out your Heroku URL. Remember? The one that is similar to Your app should be there with the same functionality as what you saw on localhost.

Congratulations! You've built your first rails app!

undefined method `task' error when using rake? v 0.9.0 broken.

When I attempted to do a migration recently, I received the following error:

rake aborted!
undefined method `task' for #<MyApp::Application:0x000001012d3be0>

It turns out that the new version of rake is broken, and it is automatically updated when you run bundle. Since that's the case, we need to roll back to v 0.8.7. I found some resources with different recommendations for fixes, but following is what worked for me:

First, we need to uninstall rake 0.9.0. In your terminal, type gem uninstall rake -v 0.9

Open your Gemfile. Add the following line gem 'rake', '~> 0.8.7' 
Save it.

Go back to your terminal and type bundle update rake.

Run your migration!

Thursday, May 5, 2011

Code Sample: my first complex Active Record Query

I experienced something the other day in Active Record. My seasoned pairing partner and I used it to do a SQL query to Active Record to pull one chunk of data that matched several criteria out of a database of many users, in many communities, that had many modes of transportation, that had all traveled different numbers of miles using those different modes of transportation. We needed the one user who had traveled the most number of miles by bicycle.

 biker_miles = User.joins(:trips => :mode).where(:modes => {:name => 'Bike'}).sum(:distance, :group => :user_id) biker_miles.max { |a,b| a[1].to_i <=> b[1].to_i }                                                                      

I need to pick this apart to really understand what it does, but I know it pulled the data we needed. It seems like this is just the magic that makes RoR so spectacular. It's like the salt on my popcorn...the cream in my coffee. More on this later.

jQuery Code Example: How to do a Hide/Show Toggle Button

This is a function that slowly hides content when you click a button, changes the value of the button from "Hide" to "Show", then slowly shows content when the button is clicked again. You'll need to create 3 files: an HTML file, a .css, and a .js Note the names of the .css files and .js files at the bottom of the HTML. Have fun playing around with the properties to give it some color or move things around.

Let's start with the HTML:
     Toggle Button Example
    <link href="togglebutton.css" type="text/css" rel="stylesheet">
  <body id="public">

      <!-- Body Header -->
      <div id="header">
          This is the Header. It can also be a logo.
        <p>Here is some text in the header! Click the "Hide" button to hide this, along with the header and the footer.
      <!-- Body Content -->
      <div id="content">
        <input type="button" value="Hide" id="toggleButton" style="float:right;">
          Content Header
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
      <!-- Footer -->
      <div id="footer">
       This is the footer! This toggles too!
    <script src="libs/jquery-1.4.4.js"></script>
    <script src="hideshow.js"></script>

Next, some CSS formatting with a stylesheet:

body {
  background-color: #CCCCCC;
  color: #333333;
  font-family: sans-serif;
  font-size: 1em;
  line-height: 1.65;

#content {
 background-color: #FFFFFF;
 border-color: transparent;
 -moz-box-shadow: 5px 7px 7px rgba(194, 194, 194, 0.3);
 -moz-border-radius: 5px 5px 5px 5px;
 -webkit-border-radius: 5px 5px 5px 5px;
 border-width: 1px;
 float: left;
 min-height: 250px;
 padding: 2%;
 width: 50%;

#content h2 {
  color: #666666;
  font-weight: normal;

#footer {
 float: left;
  padding: 18px;
  width: 64%;
 Then, the jQuery:

$(function() {
$('#toggleButton').click( function() {
  $('#footer').toggle('5000', function(){
 if ($('#header').is(':visible')) {
 } else {

Load the .html file in your browser and see what you've got! 

jQuery Tutorial: Using Themeroller to Instantly Build a Tab Navigation

I am in love with jQuery and the people who have developed the library and so generously shared, like the folks at who have developed ThemeRoller. Your life is about to get so much easier as a web developer because you don't have to reinvent the wheel!

Look at the slick tab navigation I created in literally 5 minutes (image is not actual size):

So just how easy is it?
1) Go to ThemeRoller.

2) Click on the "Gallery" tab on the top of the black navigation to the left. Notice all the widgets on the main page. Which would you like on your site?

3) Select a theme from the gallery. Notice how the colors of all the widgets change. For this exercise, I selected "Sunny".

4) If you're feeling particular or don't see the color palette you need, click the "edit" button at the bottom of the theme icon and use hexadecimal color codes to change your colors.
...OR simply click "Download" to download the theme as is. If you have done some editing, click the orange "Download Theme" button.

5) This will take you to a page that says "Build Your Download". Select the elements you will need for your project. I think keeping it simpler is better--you don't want a bunch of code you don't need. For example, I did not select "Position", since the tabs nav is the only element I am using.

6) You will receive a zipped file with everything you need, except your content of course.

7) Expand it and open the folder. Inside you will see folders that contain an index.html file, a .js file, and a .css file.

8) Edit the index.html file to remove all of the extraneous text--like the greeting and explanation, so that all that remains is the necessary html for the file and the formatted tabs navigation. you may want to leave the other two alone because they're pretty complex--unless you want to tinker with them to see what they do, or your skills are more advanced. You can always use a different .css file and .js file for the rest of the site.

You may also want to move the call to the .js file to the bottom so the page loads more quickly.

9) Replace the default content with your own, and add tabs and sections as you need them.

So there you go! Polished tab navigation, in just minutes!

If you feel that I have forgotten anything feel free to post any questions you may have below.