Call Montréal, Canada 524-949-6869

Blog

Thursday, September 30, 2010

SearchLogic ordering not working: Uses associations default scope for ordering

Came across an interesting issue with Searchlogic. Given the following models:

class Organization < ActiveRecord::Base
  has_many :contacts
  default_scope :order => "name"
end

class Contact < ActiveRecord::Base
  belongs_to :association
end

Contact.search(:first_name_or_last_name_or_assocation_name => "Nicholas", :order => "descend_by_last_name")

The search will actually use the Organization default scope to order the search, i.e. by organization's "name", not contact's "last_name". The fix, unfortunately remove the default scope from the Organization class.

This appears to be an issue with ActiveRecord, not Searchlogic.

Wednesday, September 29, 2010

Status not showing in Redmine in Issues

When you define a new status in Redmine you may notice it's not showing up when you create or edit issues in the drop-down list. To resolve this, you need to modify the workflow under Administration settings to include the new status.

This appears in the FAQ on the Redmine wiki.

Tuesday, September 28, 2010

BlankStatic updated for latest Compass, Haml, Sass; HTML5 Branch

BlankStatic got an update yesterday for the latest Compass, Haml and Sass versions. This means an update to the Gemfile and some changes to the syntax to the Sass files.

An HTML5 branch was added which will work with older version of IE as well with some JavaScript magic.

Thursday, September 23, 2010

Use Terminitor to get your Rails Development work flow setup quickly

For the average Rails Development project I have the following terminal windows setup:

  • Spork for RSpec
  • Spork for Cucumber
  • Rails Server
  • AutoSpec
  • RStakeout task for automatically running Cuke Features

Automatic Workflow Setup

That's a lot of terminals to setup and task to execute! In comes Terminitor to automatically open those windows and run the required tasks. I have the following file in ~/.terminitor/rails-dev.yml:

# Rails Server, Rspec, Cucumber with Spork Setup
---
- tab0:
- tab1:
  - rvm use ruby-1.8.7-p302@default
  - spork rspec
- tab2:
  - rvm use ruby-1.8.7-p302@default
  - spork cuc
- tab3: 
  - rvm use ruby-1.8.7-p302@default
  - script/server
- tab4:
  - rvm use ruby-1.8.7-p302@default
  - autospec -f
- tab5:
  - rvm use ruby-1.8.7-p302@default
  - autocuke

All I need to do is change into the directory of the project and execute:

  terminitor start rails-dev

I keep a blank tab, tab0 so I have a terminal window to play with, otherwise the first "tab" uses that window.

Issues

There was a only a couple of issues I came across which were pretty straightforward to work around. First, it didn't respect my default setup for rvm. I added what Ruby and Gemset to use.

The other issue was that it appeared to screw with by $PATH a bit. It added a space to the last path entry which I think was causing havoc. I just added $HOME to my path, I don't care if it messes with that.

Conclusion

I was definitely getting a little tired opening all the terminal windows for each project. This is well worth checking out.

Tuesday, September 21, 2010

Translating Booleans in I18n files

I got caught out on this today when creating a translation file that included translations for boolean values:

# config/locale/en.yml
  false: No
  true: Yes

t(false) did not translate, i.e. en, false. Ok so to be on the safe side, let's not use Ruby keyword for a key.

# config/locale/en.yml
  false_value: No
  true_value: Yes

t("#{false}_value) translated to false. OK, getting a little close, but not quite what I want.

# config/locale/en.yml
  false_value: "No"
  true_value: "Yes"

t("#{false}_value) translated to Yes. Perfect!

Saturday, September 18, 2010

Update to Firsthand Rails Template

Rails templates are a great way to get your Rails application configured just the way you like it. Today I updated my Rails template to better reflect my current development environment. It's still 2.3.x template, but will be updated when I start developing with Rails 3.x. Some of the highlights included:

  • Bundler for Gem dependencies
  • RSpec and Cucumber for testing
  • Compass, Sass, Haml and Formtastic for stylesheets and views
  • Assumes a Heroku deployment so uses Hassle to work with Sass
  • Removes directories and files that are typically used
  • Adds a default README to be configured

While this template might not work for you out of the box, hopefully it will give you some ideas on how to create your own.

Friday, September 17, 2010

Rails Application Launch Checklist

As a part of my on-going effort to publish checklists on this blog, here is my Application Launch Checklist. Let me know if there's anything missing in the comments.
Configuration and Setup
Optimizations
  • Database optimization (bullet for n + 1 queries, rails_indexes, slim scrooge, query_reviewer)
  • Page Responsiveness (Javascript and CSS caching with Jammit, Sprites, Asset hosts)
  • Background Processing (Delayed Jobs - long running processes, email, file imports and processing, HTTP calls)
Caching
  • Page Caching
  • Action Caching
  • Fragment Caching
  • Query Caching
  • Client-side Caching
  • HTTP Caching
Anything missing from Firsthand Rails Template? Plugins?
NewRelic has a great series on Scaling Rails that reviews techniques for caching and database optimizations.

Install Compass in an existing Rails application with Semantic Blueprint using Sass

compass init rails --using blueprint/semantic --syntax sass

The Other RSpec Methods: #subject, #specify, and #let

Recently I switched to RSpec from Shoulda. This switch was driven mostly by this announcement explaining ThoughtBot's intention in providing matchers for RSpec, rather than a context framework. Here are three highlights from my experience using RSpec over the last month. I call them the other RSpec methods, as their value becomes apparent after using RSpec for a while. I view their purpose as cleaning up setup code located in before blocks.

#let

Get rid of instance variables using #let. Let memoizes a block:

# before "#let"
  before do
    @valid_customer = Customer.new(:name => "Frank Reynolds")
  end

  it "should be valid" { @valid_customer.should be_valid }

  # with "#let"
  let(:valid_customer) { Customer.new(:name => "Frank Reynolds") } 

  it "should be valid" { valid_customer.should be_valid }

#subject and #specify

The subject specifies the object's behaviour that's being described:

subject { Customer.new(:name => "Frank Reynolds") }

 it "should be valid" { subject.should be_valid }

And it doesn't make sense to describe the behaviour ourselves, since RSpec will generate that for us:

subject { Customer.new(:name => "Frank Reynolds") }

 it { subject.should be_valid }

That doesn't read well, so let's use the alias "#specify":

subject { Customer.new(:name => "Frank Reynolds") }

 specify { subject.should be_valid }

But we can use an implicit subject, meaning we don't need to specify the subject (and we revert back to #it):

subject { Customer.new(:name => "Frank Reynolds") }

 it { should be_valid }

Finally, we can also use an implicit subject based on the object we are describing:

describe Customer do
  it { should_not be_valid }
 end

What are your "other" RSpec methods? Let me know in the comments.

Wednesday, September 15, 2010

Custom default attribute in ActiveRecord

When I need a default value for a ActiveRecord attribute often I will resort to using a plugin. But in reality, initializing an attribute in the #after_initialize callback is often the simplest thing that works:

class Tweet
  def after_initialize
    self.message ||= "I'm Tweeting"
  end
end         

Monday, September 13, 2010

Basic HTML Template for Designers to create a Style Guide

When I start a new front-end project coding HTML/CSS I will ask the designer to provide a style guide to outline the typography used through the website. I find when I mark-up the CSS for the typography first, before starting the grid, the overall CSS is cleaner. How do you communicate what elements need to be in the style guide? Well there are some basic elements such as headers, forms and table that I provide in a HTML file that the designer can start with. Then additional typography elements, such as typography in sidebars and call-to-actions are added to the style guide. Are there any elements you think need to be included in my basic HTML file? I like to keep it relatively simple so I don't add things like definition lists, but perhaps I should. Let me know.

Rails Validations can be any ActiveRecord Model Instance Methods

class Customer

  # first_name: string
  # last_name: string

  validates_presence_of :first_or_last_name, :message => "must be provided"

  def first_or_last_name
    first_name || last_name
  end

end

Saturday, September 11, 2010

How to get the options for a named_scope

class Video < ActiveRecord::Base
  named_scope :highest_scores, :order => "score DESC, id"
end

Video.highest_scores.proxy_options # => {:order=>"score DESC, id"}

Friday, September 10, 2010

Configure RMagick gem in a Rails 2.3.x application

# environment.rb
config.gem "rmagick", :lib => 'RMagick', :version => "2.13.1" # version number optional

Autospec problem, autospec exiting without results

A little frustration today with autospec (to clarify, not autospec's fault). I had recently installed RVM and started using gemsets (really this is amazing). When setting a default gemset I installed a bunch of gems including Paperclip 2.3.3. Unfortunately, Paperclip's dependencies include ActiveSupport and installed version 3.0.0. My current default gemspec is setup for rails 2.3.8, I have built a separate one for Rails 3.0.0 on Ruby 1.9.2. For some reason, with ActiveSupport 3.0.0 installed, caused autospec to exit without any results.

(Not running features.  To run features in autotest, set AUTOFEATURE=true.)
loading autotest/rails_rspec
style: RailsRspec

The solution, simply uninstall ActiveSupport 3.0.0 (and any other 3.0.0 Rails dependencies) Paperclip 2.3.3 runs just fine with 2.3.8. This really makes sense since I want to keep a clean 2.3.x environment. To be clear, I had not installed Rails 3.0.0 in this gemset.

BlankStatic Version 1 released with "Bundled" Gems, Onward to Version 2

My template for creating static sites and prototyping templates for web applications and Radiant CMS templates, BlankStatic, has reached a version 1 release. Admittedly BlankStatic hasn't seen much love lately, and I wanted to upgrade the versions of Haml, Sass and Compass it's using. However, this posed a problem for working with older sites using the current version. Enter Bundler.

Bundler allowed me to specify what Ruby Gems my tagged version of the template required in the Gemfile.

# Gemfile
source "http://rubygems.org"

gem "haml", "2.2.0"
gem "compass", "0.8.16"
gem "staticmatic", "0.10.1"

Perfect. A bundle install installed the gems I needed and create the Gemfile.lock that includes specific dependencies and I checked those both into git.

# Gemfile.lock
GEM
  specs:
    cgi_multipart_eof_fix (2.5.0)
    compass (0.8.16)
      haml (>= 2.2.0)
    daemons (1.1.0)
    fastthread (1.0.7)
    gem_plugin (0.2.3)
    haml (2.2.0)
    mongrel (1.1.5)
      cgi_multipart_eof_fix (>= 2.4)
      daemons (>= 1.0.3)
      fastthread (>= 1.0.1)
      gem_plugin (>= 0.2.3)
    staticmatic (0.10.1)
      haml (>= 2.0)
      mongrel (>= 1.0)

PLATFORMS
  ruby

DEPENDENCIES
  compass (= 0.8.16)
  haml (= 2.2.0)
  staticmatic (= 0.10.1)

However, I still had issues with the bin executables when running the server. For example, /usr/loca/bin/staticmatic points to the newer version of the StaticMatic gem, while I need to use an older version. No problem, bundle those executables using bundle exec. Now I can execute the bin/staticmatic preview . in the root of my static site. Super cool.

Now that I have a "freezed" version, I will start working on version 2. This will include an upgrade to the latest dependent gems and changes to the Sass templates to make them compatible with the new syntax.

Thursday, September 9, 2010

How to display Facebook Profile information when using FBGraph Ruby Gem for an Authorized User

When using the FBGraph Gem for Facebook I wanted to display profile information for the logged in user authorized with Oauth2. It wasn't immediately clear to me from the documentation on how to do that.

Once you have a authorized user and a client instance, call:


You can then access various attributes:


Also note there is a fgraph gem as well, don't get them mixed up!

RSpec #stub vs. #stub!

Confused by #stub vs. #stub!? Consider #stub! deprecated and use #stub. #stub is simply an alias for #stub!. #stub! was defined in the API at a time when RSpec's authors weren't clear on the intention of "bang" methods in Ruby. Quoting David Chelimsky's email on RubyForge:

The original method was stub!, which I will confess to introducing, and for the wrong reasons, due to my misunderstanding of the meaning of ! in ruby methods. I recently added stub (with no !) with no particular fanfare, as I don't intend to remove stub! (at least not any time soon). Right now the docs don't make it clear, so I need to fix that - but I'd say that stub() is the method to use and stub!() is there for backwards compatibility.

The confusion is compound in The RSpec Book (B15.0 printing, July 29, 2010) where there is as single reference to #stub! on page 199.

References:

Wednesday, September 8, 2010

Class Methods Called Against Associations in Active Record

Did you know you can call class methods against associations? Admittedly this is a trivial example, but here goes:


Class methods also work against named scopes. I will provide a "good" example of this later in the week.

Ruby Hook Methods

Here is a list of all the hook methods in Ruby. This list is taken from the screencast Some Hook Methods in the The Ruby Object Model and Metaprogramming series.

Method-related Hooks

  • method_missing
  • method_added
  • singleton_method_added
  • method_removed
  • singleton_method_removed
  • method_undefined
  • singleton_method_undefined

Class & Module Hooks

  • inherited
  • append_features
  • included
  • extend_object
  • extended
  • initialize_copy
  • const_missing

Marshalling Hooks

  • marshal_dump
  • marshal_load

Coercion Hooks

  • coerce
  • induced_from
  • to_xxx

Monday, September 6, 2010

Radiant Training Resources and Email Template

For most Radiant projects, I do one-on-one training with the client. This allows them to get familiar with Radiant's administration interface and customizations. I also have a "site" extension, which encapsulates any basic customizations and also add documentation relating to layouts, page types and styles used. This is implemented using the help extension.

Radiant Screencasts

One of the most useful resources I have developed is a series of screencasts that cover a basic Radiant installation and FCKEditor. Please note that these are based on Radiant 8.x. I hope to upgrade these in the near future for Radiant 9.x.

Before the one-on-one session, I send an email to the trainnees, asking them to review the documentation and screencasts beforehand. This is the email template I use:

Email Template

In preparation for you training and for reference at a later date, you have access to online documentation and a series of videos on how to use Radiant, the Content Management System (CMS) for your website.

Documentation

For an introduction to the Radiant CMS:

http://example.com/admin/help

Customizations made to the Radiant CMS for your website:

http://example.com/admin/extension_help/site/all

Videos: Introduction to Radiant

The first series of videos introduces Radiant CMS, how to create and edit pages etc:

http://vimeo.com/album/137118/format:detail

Videos: Using the FCKEditor

The second series is how to use the FCKEditor, a WYSIWYG editor for edit page content. This series describes how to insert images, create links etc.

http://vimeo.com/album/137177/format:detail

Training

I would recommend the participants review the documentation and videos before the training session. All the material will be covered again in the session, but it is helpful to get familiar with Radiant before hand.

The training will cover:

  • An introduction to Radiant CMS
  • Using the FCKEditor
  • Customizations of the Radiant CMS for your website

Training Requirements

Access to a computer with an internet connection will be required.

Please let me know the date and time for the training session and who will be attending. I look forward to helping you get started in maintaining your new website!

Saturday, September 4, 2010

Shopify (eCommerce) Pre-Launch Checklist

Here is a basic pre-launch checklist I use when working on a Shopify Project. Of course this checklist can be used on any type of eCommerce project:

Setup the following:

  1. Email Notifications
  2. Shipping Handling
  3. Taxes
  4. Payment Gateway
  5. Google Analytics
  6. Redirect domain name

And don't forget training the client in using the administration backend. Shopify has a great set of resources for support and training:

The first thing you will probably want to do is help your client understand how to organize their products.

Usability Issue on American Airlines Reward Travel

I wonder how many times some has mistakenly clicked "Start Over" instead of go":

american-airlines.jpg

The solution would be to change the "Start Over" button to a text link and enlarge and relabel the "Go" button. After all the "Start Over" is a secondary to "Go". Here's my solution:

american-airlines-fixed.jpg

Ruby RDoc Example

This is an example RDoc file I sometimes refer to which illustrates documenting classes and methods. Yes I now I should probably move to YARD.

Friday, September 3, 2010

Radiant Releases Now Listed on the Wiki Page

It's now been a week writing my daily stand-up blog posts. I was prefixing the title with "24hrs Firsthand" to identify them as my daily post, but really this seems redundant and just added a lot of noise with no value. After all a blog is a journal, and I suspect readers don't need to know it's my "daily blog post". I will still tag them with stand-up. Now onto some real content...

Radiant Release Notes

Instead of doing my normal wrap-up of yesterday's events, I spent some time this morning listing the Radiant releases on the wiki, with links to release notes, change logs and upgrade notes. I had this in a text file on my local computer -- seemed silly not to share it. I'm sure everybody, new and old to Radiant, will find this very useful.

Thursday, September 2, 2010

Leave a project how you would like to find it

I started a new CMS project yesterday with Radiant. One aspect I am really focusing on is to ensure that all the "other" details are taking care of during the development, so when another developer needs to work on it, they can get started on it as quickly as possible.

The new Bundler and Rails 2.x config.gem have certainly helped with installing dependent gems, but I still think it's beneficial to have a step by step guide in the form of a README file on getting the application running and any other aspects of the application the developer should know about.

GitHub presents the README file of the homepage of the repository.

README file on Github

Please replace the default README file in your Rails or Radiant application (or any other open source application). Here's a basic outline of what you could include:

  • Application setup and database bootstrapping
  • Testing frameworks used and how to run the tests
  • References used on the project (for example, if you used a third-party API, link to those documents)
  • Any other interesting notes that you discovered during development, but would have liked to have known before you got started
  • Populating the database with "demo" data
  • How to easily preview application emails (hint: rake tasks)

Are there any other items that should be in the README? Do you have any links to examples of great README's?

Wednesday, September 1, 2010

Radiant 0.9.1 and Globalize2 Extension

I've started a new project using Radiant. After doing a review of other Ruby on Rails-based CMS projects, Radiant is still my first choice.

This project will be a bi-lingual website and the Globalize2 Extension does a brilliant job of meeting this requirement. You can view the screencast below to get a feel for it's functionality.

However the "master" project repository is not compatible with Radiant 0.9.1. You will need to use this repository instead. I'm thankful for GitHub and forking!

Developing Ruby on Rails applications and custom Content Management Systems in Montréal. Contact Firsthand.