TwitterFacebookGoogle

Sublime Text 2 Shortcuts for Ruby on Rails

When it comes to full-featured text editors for RoR development, Sublime Text is hard to beat. Here are some shortcuts that add to the awesomeness of Sublime Text:

Common Shortcuts

Ctrl+P: Find Files
Ctrl+KB: show/Hide Mini-Bar
Ctrl+W: Close file.
Shift+Alt+1 OR 2 OR 3: For creating/closing panels
Ctrl+[ OR ]: Indent OR Un-indent
Ctrl+L: Highlight-line
Ctrl+KK: Delete line
Ctrl+G: Go to line

For Ruby Tests

Clone the repo: https://github.com/maltize/sublime-text-2-ruby-tests and follow setup instructions

Ctrl+Shift+T: Run all tests
Ctrl+Shift+R: Run a single test
Ctrl+Shift+E: Run last ruby test

ERB commands

Clone the repo: https://github.com/eddorre/SublimeERB

Ctrl+Shift+.: ERB Snippet
Ctrl+Enter: Move to next line

Tab-triggers

“des”+tab for describe
“it”+tab for it block
“before”+tab


Sublime Tutorial by Michael Hart:
http://www.youtube.com/watch?v=05x1Jk4rT1A

Happy Coding!

Twitter Email Linkedin Digg Stumbleupon Subscribe

Interview Question : Following DRY

I’ll be posting potential interview questions that I come up with from time to time on my blog – so that I can refer to it later and also to share them with others. Here is one I came up with today:

Re-write the following code-snippet so that it complies with the DRY principle:

 
if(!_autoenroll)
{
     if(displayEnrollPage == true)
     {
        ltlView1.Text = "Enroll Online - Page 1 of 4";
        ltlView2.Text = "Enroll Online - Page 2 of 4";
        ltlView3.Text = "Enroll Online - Page 3 of 4";
        ltlView4.Text = "Enroll Online - Page 4 of 4";
     }
     else
     {
        ltlView1.Text = "Enroll Online - Page 1 of 3";
        ltlView2.Text = "Enroll Online - Page 2 of 3";
        ltlView3.Text = "Enroll Online - Page 3 of 3";
 
        // don't set header for the 4th page because it wont be visible.  
    }
}
else 
{ 
     if(displayEnrollPage == true)
     {
        ltlView1.Text = "Enroll Online - Page 1 of 3";
        ltlView2.Text = "Enroll Online - Page 2 of 3";
        ltlView4.Text = "Enroll Online - Page 3 of 3";
     }
     else
     {
        ltlView1.Text = "Enroll Online - Page 1 of 2";
        ltlView2.Text = "Enroll Online - Page 2 of 2";
 
       // don't set header for 4th page because it wont be visible.       
    }
}

No, I won’t be posting the answers. But feel free to suggest one inside the comments section!

Twitter Email Linkedin Digg Stumbleupon Subscribe

Recently launched web application built via Ruby On Rails

Wanted to write a short blurb on a web application that I recently launched. You can visit it at: http://www.spryee.com. It’s a free and easy-to-use goal & activity tracker.

I created the application in Ruby on Rails 3.2 using the following additional languages/packages/tools:

- CoffeeScript: For all my UI interactions and making AJAX calls
- Twitter Bootstrap: For my UI framework.
- Google Visualization API: For generating charts & graphs
- SASS: For all my style-sheets
- Image Sprites: For all my images
- GIMP: For doing all types of image manipulation
- Jekyll: For creating the blog
- RSpec: For all of my unit-testing

In addition to this, I also used the following gems:

- Authlogic : For user & user-session management. Takes cares of everything having to do with user creation and session management such as, password encryptions, logins, forgot password functionality, cookies, remember-me, login counts, etc.

- GON: Allows you to easily set and send JSON to and from the server to the browser and vice-versa. Very handy!

- simple-form: The best at form generation. Easy to get started and very extendable.

- Rabl: Let’s you define your JSON object using Ruby! How cool is that?

- bootstrap_sass: Bundling support for twitter bootstrap.

- will_paginate: For paginations.

- google_visular: This gem provides a Ruby-based API for interacting with the Google Visualization APIs (which are js-based). It doesn’t support AJAX-based refreshes of the charts but I was able to make it work by making a few modifications. I’ll blog on it another day.

- bloggy: This gem creates a Jekyll blog for your existing Rails app. I had my blog ready to go in just a few hours!

I deployed the web-app on Heroku because 1) it takes away virtually all of pain that’s associated with deployment and because 2) it’s completely free until you’ve got enough users to where an upgrade becomes necessary.

Hope this helps someone who might be getting started with Ruby on Rails!

Twitter Email Linkedin Digg Stumbleupon Subscribe

Rendering Icons as links in ASP .NET MVC

Modifying the behaviors of HTML helper methods such as ActionLink is a pain and requires quite a bit of code. Sometimes, however, you get lucky and are able to avoid it. What follows is once such case.

Here is one quick way that you can use to render an icon as a link in ASP .NET MVC.

First, create a CSS style for the icon:

 .print-icon {
    background: url("/assets/print-icon.png");
 }

Next, use it when generating the link:

  @Html.ActionLink(" ", "Action", new { id = /* blah */ }, new { @class = "print-icon" }

And, that does it!

Cheers!

Twitter Email Linkedin Digg Stumbleupon Subscribe

Cloning an object for creation in Ruby

Ruby provides two methods for creating a copy of an object: clone() and dup(). Starting from Rails 3.1, the behavior of these methods has somewhat changed. In this post, I’ll point out some of the differences as they relate to record creation and also share some helpful pointers when constructing and saving a new object-graph.

Let’s say we’ve got the following classes:

class Unit
  attr_accessible :name, :division_id
  belongs_to :division
 
  validates :name, presence :true
  validates :division, presence :true
 
  validates_uniqueness_of :name, :scope => [:division_id], :case_sensitive => false, :on => :create	 
end
 
class Division
  attr_accessible :name, :user_id
  belongs_to :user
 
  validates :name, presence :true
  validates :user, presence :true
end
 
class User
  #... your good 'ole user class
end

The Scenario

What we’d like to do is create a copy of an existing unit, add it to a brand-new division that belongs to some user and then call user.save(). What we’d expect to see is that:

- A new division is created and associated with the user
- A new unit is created and associated with the newly created division

Understanding clone vs. dup

Let’s first look at the major differences between clone() and dup() so we know which method to use for our specific scenario.

One difference is that clone() does not mark the copy as a new_record while dup() does:

  >> u_clone = Unit.first.clone
  >> u_clone.new_record?
  >> = false
  >>
  >> u_dup = Unit.first.dup
  >> u_dup.new_record?
  >> = true

As a consequence, dup() blanks out the id, created_at and updated_at attributes whereas clone() does not.

Another difference is that clone() copies over the contents plus the internal state and singleton methods whereas dup() only copies over the contents.

Creating and persisting our object graph

In our case, because we wish to create a new unit and add it to a new division, it looks like dup() is what we need. Let’s give it a shot and see what happens:

 >> usr = User.first
 >> d1 = usr.divisions.build({ name: "Divison 1" })
 >> d1.units << Unit.first.dup
 >> usr.save
 >>

What we are doing in the code snippet above is picking the first user, adding a new Division to the user’s divisions collection, adding a new Unit to the divison and then calling save on the user. Think it’ll work? Let’s look at the next line to see what transpired:

  >> usr.save
  >> = false

Oops, didn’t work! Let’s look at the error messages to see what went wrong:

  >> usr.save
  >> = false
  >> usr.errors
  >> [divisions: 'is invalid']
  >> usr.divisions.last.errors
  >> [units: 'is invalid']
  >> usr.divisions.last.units.first.errors
  >> [division: "can't be blank"]

Hmm…division can’t be blank! If you scroll to the class definition of Unit, you’ll notice that we have a validation rule that enforces that division can’t be blank. If we got rid of that validation rule then the above usr.save() would passed. This is because Rails is smart enough to recognize that a new unit is being added to a new division and so it’ll first create the division inside the database, assign the division to unit and the create the unit inside the database.

So, why doesn’t that work with the validation rule being present? Because Rails runs validation on the entire object graph before persisting anything to the database! Since, in our case, we are adding a new unit to a new division, unit.division is nil and hence our validation that states “Unit must have division” fails and nothing is persisted. To make this work without removing the validation rule, what we’ll need to do is add the following additional lines:

 >> u_dup = Unit.first.dup
 >> u_dup.division = d1

Or a better approach is to override the dup() method so that it accepts division as a parameter:

class Unit
   ...
 
  def dup(division) 
    u_dup = super()
    u_dup.division = divison
    u_dup
  end	 
 
  ...
end

And now the following will work successfully:

 >> usr = User.first
 >> d1 = usr.divisions.build({ name: "Divison 1" })
 >> d1.units << Unit.first.dup
 >> usr.save
 >> = true

Hopefully, this gave you some insight into how clone() and dup() work and it’ll save you some headache the next time you need to persist an object graph!

Twitter Email Linkedin Digg Stumbleupon Subscribe

Bulk INSERT from within a Rake task

Recently, I had to insert a ton of sample data into our test database to facilitate testing. My first attempt was to use the activerecord-import gem. Looks pretty promising but for some odd reason I just couldn’t get it work from inside a Rake task. It kept inserting data in sequential order instead of doing BULK inserts.

Well, after some R&D, I came across a “simpler” solution that doesn’t require the use of any additional gems. It turns out that all I had to do was wrap all of my inserts inside one transaction. This speeds up the inserts by a HUGE factor when compared with sequential inserts – ~200 ms vs. 1000 ms for about 10 records! An additional benefit of this approach is that all of your model validations still run as they normally would.

Below is a code snippet:

def make_users
  puts "Creating users..."
  users = []
  10.times do |n|
    users << User.new(
      full_name: "User #{n}", 
      email: "user_#{n}@test.com", 
      password: "foobar",
      password_confirmation: "foobar")
  end
  User.transaction do 
    users.each { |u| u.save }
  end
  puts "Finished creating users."
end

Bye bye, activerecord-import gem! I am sticking with the transaction wrapper!

Twitter Email Linkedin Digg Stumbleupon Subscribe

Show/hide various sections of a page using JQuery and CSS

In this post I’ll go over how you can utilize JQuery and CSS classes to show/hide various parts across the different sections of a page without creating a mess!

The Challenge
You’ve got a wizard-like page with multiple steps and you want to be able to show/hide various elements based upon the current step. Below is a dumbed-down example:

The colored boxes represent the parts that are being shared across the various sections of the page. For instance, the green box is being shared by the ‘Image Selection’ and ‘Order Confirmation’ sections. While the red box is being shared by all three sections.

So the challenge is: How do we show/hide these various parts across the sections of the page without making a mess? And by mess, I refer to duplicate code and/or little <% if..then %> snippets scattered throughout the page.

The Solution
By using some CSS/JQuery trickery, of course! What we’ll do is introduce some CSS classes that we will then apply to the various parts for which we need to handle visibility. Here are the classes that we will need:

  • section – Represents a section
  • requestor – Represents the requestor section
  • image-selection – Represents the image selection section
  • confirmation – Represents the order confirmation section

The CSS classes will then be applied to the various parts based upon the section inside which the part is to be shown:

<div>
  <input type='hidden' id='section-to-show' />
  <table>
    <tr>
      <td>Request Type:</td>
      <td class='section requestor'>
        <select>...</select>
      </td>
      <td class='section image-selection confirmation'>
        <%= selectedRequestType %>
      </td>
    </tr>
    ...
    <tr>
      <td>First Name:</td>
      <td><%= firstName %></td>
    </tr> 
    <tr>
      <td>Last Name:</td>
      <td><%= lastName %></td>
    </tr> 
    <tr class='section requestor confirmation'>
      <td>Email</td>
      <td><%= email %></td> 
    </tr>
    ...
    ...
    <tr class='section image-selection confirmation'>
      <td>Image</td>
      <td class='section image-selection'>
        Browse...
      </td>
      <td class='section confirmation'>
        <img src='..' />
      </td>
    </tr>
    ...
  </table>
</div>

A few things to highlight:

– The hidden input field ‘section-to-show’ indicates the section to display. It’s value is set by the server-side code.
– There are two table columns inside the first table row. Only one will be visible based up the section that is being displayed.
– The first name and last name table rows don’t have any classes applied to them. This is because they are always visible.
– The last table row shown above gives an example of how you can make the visibility conditional for both the table row and the table column.
– I skipped various rows in the HTML form above to save some typing and to avoid being repetitive.

And now for the JQuery:

  $(document).ready(function(){
 
    // hide all sections to begin with
    $('.section').hide();
 
    current_section = $('#section-to-show').val();
    $("." + current_section).show();
  });

And there you have it – a cleaner alternative to showing and hiding various parts across the sections of a page!

Twitter Email Linkedin Digg Stumbleupon Subscribe

Writing integration tests for ASP .NET with Selenium 2.0 – Part 1

This is the first in a series of posts on writing integration tests for ASP .NET using the Selenium 2.0 web application testing system.

UPDATE: This post was updated on April 15, 2012 to explain how to setup and configure Selenium 2.0.

In this post, I explain what Selenium is, why use it and how to setup and configure it. In the next subsequent posts, I’ll do a code walk-thru and also share some advanced scenarios.

What is Selenium?
The best description of Selenium is probably the one mentioned on their website:

“Selenium automates browsers. That’s it. What you do with that power is entirely up to you. Primarily it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration tasks can (and should!) also be automated as well.”

Why use Selenium?
There are other integration testing web frameworks out there such as WaitN or the Lightweight Test Automation Framework for testing ASP .NET web apps. So, why use Selenium? Here are the main reasons why picked it:

  1. Selenium allows you to record test scenarios manually (by browsing to specific pages and clicking buttons, etc.) as well as programmatically (by coding up a test case). Thus the tool can be used by both developers and QA’s. You can even use a combination of recorded test scenarios and C# test cases to integration test your application.
  2. One feature that I really liked is that you can export a recorded test scenario as a C# test-case! This technique can be used to drastically speed up the Selenium learning curve since it spits out code that you can use inside C# test-case. For instance, when you’re unsure how to code up a specific scenario you can manually record it and then export it to see what the code needs to look like.
  3. The recorded scripts can be used as a tool to speed up manual testing. For example, I never manually login into the web application that I am currently implementing anymore. Instead I run a test scenario that I had previously recorded, conveniently named Login, that logs me in. No more manually typing in username/password! You can use this technique to directly land on specific pages and/or fill-in and submit forms as well. This adds up to save you boat loads of time during your manual testing.
  4. Finally, the test recorder is a small Firefox plugin and integrates real nice with Firefox.

Convinced? Awesome! Let’s move on to setting up Selenium…

Initial Setup
There are two parts to setting up Selenium:

  1. Installing the Selenium IDE: A Firefox plugin that allows you to manually record test scenarios. Find and download the Selenium IDE plugin from the Selenium Downloads section. After it downloads, fire up the Firefox browser -> Go to Add Ons from the Main Menu -> Click the Settings icon -> Select the Install Add-On From File option -> Click Install Add-On.
  2. Installing the Selenium 2.0 WebDriver for .NET: Accepts commands from your C# test cases and automates the browser. Using the NuGet Package Manager Console, run the below commands to install the Selenium packages. Make sure you select your test project as the “Default project” inside the Package Manager Console before running the commands. This way the DLLs will get added to the correct project.

    Install-Package Selenium.WebDriver
    Install-Package Selenium.Support

    Okay, at this point, we should be all set with Selenium. Verify the following:

    - You are able to record a test scenario: Fire up Firefox. On the Main Menu, under Web Developer, you should now see a Selenium IDE option. Or you can use the Ctrl+Alt+S shortcut key to bring it up. Click the record button on the top right, browse to goggle.com, and search for something. Click the record button again to stop the recording. Now try running the script by clicking the play button and see what happens. Make sure you are already on the google.com page when you click the Play button. Hopefully, it worked. If not, call me. I’ll help you out and I only charge a $150/hr. Just kidding. If it doesn’t work then try re-installing the plugin, I guess. :)

    - You are able to write and run C# integration test-cases using Selenium – This is what I go over in my next post on Selenium.

    Twitter Email Linkedin Digg Stumbleupon Subscribe

Dynamically creating input fields on tab via CoffeeScript and JQuery

Below is my very own, very first, super-clean, super-sexy CoffeeScript snippet that dynamically appends input fields as the user tabs through the current input field. The source-code is on the left. On the right you can actually play with it and see it in action!

inputId = 1;
 
jQuery -> 
  $("#fields :input").live 'keydown', (e) ->
    if isModifierKeyPressed e
      return 
 
    if e.keyCode in [9, 13]
      e.preventDefault
 
      if isLastActivity($(this).attr 'id')
	addAnotherTextInput();
 
      $(this).next().focus();
      return false
 
isModifierKeyPressed = (e) ->
  e.ctrlKey or e.altKey or e.shiftKey
 
isLastActivity = (inputFieldId) ->
  inputNumber = 
    (Number) inputFieldId.split('activity')[1]
  inputNumber == inputId
 
addAnotherTextInput = ->
  inputId++
  $("#fields").append getInputField inputId
 
getInputField = (inputId) ->
  return "<input type='text' id='activity#{inputId}' 
                 class='input-super-large' 
                 placeholder='Type something and then press tab' />"
Twitter Email Linkedin Digg Stumbleupon Subscribe
CyberChimps