About

Posts by :

Save Only Changed Attributes in Backbone.js

Backbone.js syncs all model data to the server by default regardless of what actually changed. This makes a lot of frontend tasks and debugging much easier, but for some models, sending all the data every time is overkill.

Here’s a quick extension to backbone models and collections to only sync changes. Just call model.saveChanges instead of model.save and only your changes will be synced.

# CoffeeScript
cx_backbone_common =
  sync: (method, model, options) ->
    # Changed attributes will be available here if model.saveChanges was called instead of model.save
    if method == 'update' && model.changedAttributes()
      options.data = JSON.stringify(model.changedAttributes())
      options.contentType = 'application/json';
    Backbone.sync.call(this, method, model, options)

cx_backbone_model =
  # Calling this method instead of set will force sync to only send changed attributes
  # Changed event will not be triggered until after the model is synced
  saveChanges: (attrs) ->
    @save(attrs, {wait: true})

_.extend(Backbone.Model.prototype, cx_backbone_common, cx_backbone_model)
_.extend(Backbone.Collection.prototype, cx_backbone_common)

RSpec + Capybara + Devise Login Tests

For the new version of Connect.Me (in development), the interface is mostly driven through AJAX interactions. In the past, I’ve used Cucumber + Capybara to test JavaScript, but I really don’t like the Cucumber syntax and slow tests. I recently switched to RSpec request specs with Capybara. The only problem is testing testing JS on pages that require a login.

Since Capybara runs in a different thread from the tests, session data is not available. So the Devise sign_in method does nothing for Capybara.

There are basically two solutions to get Capybara to authenticate:

  1. Use Capybara to login through a Devise login form by posting the user’s email and password
  2. Set session data in Capybara to simulate a login (basically do the same thing that Devise’s sign_in does)

For speed of tests reasons, I’d prefer to just set session data. After Googling around, I found this solution and modified it a bit.

# spec/support/request_helpers.rb
require 'spec_helper'
include Warden::Test::Helpers

module RequestHelpers
  def create_logged_in_user
    user = Factory(:user)
    login(user)
    user
  end

  def login(user)
    login_as user, scope: :user
  end
end

Now you just need to call create_logged_in_user and you’re good to go.

describe "user settings" do
  let(:authed_user) { create_logged_in_user }

  it "should allow access" do
    visit user_settings_path(authed_user)
    # should be good!
  end
end

Resque Admin in Rails 3 Routes with CanCan

Resque is a background jobs queue that’s highly recommended over Delayed::Job if you are processing a lot of jobs. It uses Redis as the backend which doesn’t suffer from db related bottlenecks under high load.

Resque comes with a built-in admin interface that’s Rack compatible. In Rails 3, you can mount the Resque server admin directly in your routes.rb file.

mount Resque::Server, at: '/resque'

But you’ll definitely want to add password protection. Ryan Bates in his Resque RailsCast covers the basics of using Devise and HTTP auth. However, you’ll probably want to hook into your existing ACL system. In my case, I’m using CanCan.

CanCan is not available in the routes.rb by default, but it’s pretty easy to manually load the user and check permissions.

# routes.rb
namespace :admin do
  constraints CanAccessResque do
    mount Resque::Server, at: 'resque'
  end
end
# config/initializers/admin.rb
class CanAccessResque
  def self.matches?(request)
    current_user = request.env['warden'].user
    return false if current_user.blank?
    Ability.new(current_user).can? :manage, Resque
  end
end
# ability.rb
class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= User.new
    if user.is_admin?
      can :manage, Resque
    end
  end
end

You’ll need User.is_admin? method or change the logic in Ability to suit your project.

Now an authenticated user with is_admin? == true will be able to access Resque admin. Other users will get a 404 since no route matches.

Thanks to Arcath’s blog post for initially pointing me in the right direction.

Rescuing from Rack::Timeout to Close MongoDB Connection

I’m using Rack::Timeout on Heroku to kill requests before Heroku’s 30 second limit is reached. This helps applications play nice with cloud infrastructure but can cause some unexpected bugs with MongoDB connections being reused by the next request.

The errors showed up as…

Mongo::ConnectionFailure: Expected response 372 but got 371

Mongo ruby driver >=1.3 catches the reused request and raises an error, but this still means the first and next requests both returned errors. It’s much better to catch the initial timeout and close the connection.

It seems like rescue_from Timeout::Error in ApplicationController should work, but for some reason the exception passed in is a Class and not Timeout::Error – most likely due to Rack::Timeout wrapping the entire app.

I googled around and couldn’t find a more elegant solution, but the below snippet in ApplicationController does the trick.

  # note: can not rescue from Timeout::Error directly because a timeout from Rack::Timeout ends up passing in Class as the exception
  rescue_from Exception do |exception|
    # catch Timeout::Error or message from Rack::Timeout
    if exception.is_a?(Timeout::Error) || /execution expired/ =~ exception.message
      # prevent subsequent requests from reusing this mongo connection
      Mongoid.database.connection.close
    end
    raise
  end

As a side note, Heroku’s new cedar stack does not have the 30 second limit if you’re streaming data – Rails 3.1 supports streaming.

Validating a Single Attribute in Rails ActiveRecord

Checking a single attribute on a model for validity doesn’t seem to be possible in Rails. Or at least I couldn’t find a quick answer googling around or looking through the ActiveRecord code.

What I really want to do is pass a hash into valid? with the attributes I want to validate or have an attribute_valid? method. This level of granularity is often useful in AJAX heavy apps. For instance, checking for username availability and validity as the user types during username selection.

Here’s a quick solution for a User model.

def attribute_valid?(attr, value)
  u = User.new(attr => value))
  u.valid?
  !u.errors.has_key?(:username)
end

Rails 3′s unobtrusive javascript support…

Rails 3′s unobtrusive javascript support makes it easy to integrate jQuery UI Autocomplete and any backend or custom query you want. There’s a Rails3 jQuery Autocomplete gem already available on github, but it’s not very RESTful and makes a lot of assumptions that might not fit your application.  So why not roll your own?

It’s easy.

First, make sure your rails app is setup with jQuery support.

Next, download jQuery UI Autocomplete, copy the appropriate files into your javascripts and stylesheets directories, and make sure the JS and CSS files are loading properly in your app.

Here’s the general process I use to setup autocomplete for Rails 3:

In the controller

  1. create a method to handle the autocomplete search request

In routes

  1. add a route for the method you created in the controller – this is your autocomplete search endpoint

In the view

  1. add a text field with a unique class name like ‘autocomplete’
  2. add a unique data attribute like ‘data-endpoint’ to the text field and set it to the path of your autocomplete endpoint

In application.js

  1. enable jQuery Autocomplete on any DOM element with the class ‘autocomplete’ (or whatever you used in the view)
  2. use the value of data-endpoint as the source URL for the jQuery Autocomplete widget

In the following example, I’m tagging a user and using autocomplete to help suggest tags.

controllers/users/tags_controller.rb

class Users::TagsController < ApplicationController
  respond_to :json
  skip_before_filter :authenticate_user!, :only => [:index]

  def index
    @user = User.find(params[:user_id])
    @tags = Tag.where(["LOWER(name) LIKE ?", "#{params[:term].downcase}%"]).select('name').limit(15).map {|tag| tag.name}
    respond_with(@tags)
  end

  def create
    @user = User.find(params[:user_id])
    tag = @user.tags.create!(params[:tag])
    flash[:success] = 'Tag added'
    redirect_to user_path(@user)
  end
end

The tags controller has two methods. One for creating a tag, and one (index) for handling tag autocomplete searches.

The index method expects user_id and term params. In this example, the user_id is being handled in the path /users/:user_id/tags and jQuery Autocomplete sends in the term param.

routes.rb

resources :users do
  resources :tags, :only => [:index, :create], :controller => 'users/tags'
end

This creates a /users/:user_id/tags route and a users_tags_path helper to use in your views.

views/users/show.html.haml

= form_for [@user, @user.tags.build] do |f|
  .field
    = f.label :name, 'Tag'
    = f.text_field :name, :class => 'autocomplete', :'data-endpoint' => user_tags_path(@user)
  = f.submit 'Add Tag'

javascripts/application.js

jQuery(function($){
  $('.autocomplete').each(function(){
    var self = $(this);
    self.autocomplete({source: self.attr('data-endpoint')});
  });
});

That’s all there is to it. You can easily modify your controller and model code to use MongoDB, Solr, Redis, or whatever you want.

Happy coding.

Git Hacks for OSX

Use these git config settings and tools to make your life easier.

Git tab autocomplete for OSX – enables tab autocomplete for most git commands

Git autocomplete is super helpful if you have long branch names.

Add the below code to your ~/.gitconfig file to enable color and popular short codes.

[color]
	ui = auto
[alias]
	co = checkout
	br = branch
	st = status

GitX – git graphical viewer – better than gitk

The brotherbard fork of gitx has some recommended improvements.

Thanks to Ben Woolsey for all these tips.  Ben is working with us on a new startup.

Rails 3 + STI: Making Associations Work Properly

I really like the idea of Single Table Inheritance (STI) for all sorts of applications to keep code DRY and make it easier to organize object behavior. The only problem is that Rails 3.0.3 doesn’t fully support STI with association collections.

Let’s say you have a User model that has many badges. The badges will be stored in the badges table but you want to implement each badge in a subclass. All you have to do is make sure there’s a :type field of type string in your badges table and Rails STI support should take care of the rest (well, in theory).

class User < ActiveRecord::Base
  has_many :badges
end

class Badge < ActiveRecord::Base
  belongs_to :user
  def award
    raise "Must implement in subclass"
  end
end

class Badges::Superhero < Badge
  def award
    user.status = 'superhero'
  end
end

Now you can do cool things like create a new Superhero badge and add it to a user’s badge collection.

user = User.first
badge = Badges::Superhero.new
user.badges << badge

But for some weird reason, you can’t use the best practice of building a badge directly from the user’s badges collection.

user = User.first
badge = user.badges.build(:type => Badges::Superhero)
# badge.class == Badge

This is particularly annoying if you’re trying to create new badges from a form where :type is a drop down menu.

The reason the collection build method doesn’t work as expected is because :type is a protected field and ActiveRecord::AssociationReflection doesn’t fully support STI (at least in Rails 3.0.3).

Not to fret, hacks to the rescue!

You have two options to make STI work as expected.

Option 1: Override the Badge.new method to handle :type

class Badge < ActiveRecord::Base
  belongs_to :user
  self.abstract_class = true

  class << self
    def new_with_cast(*a, &b)
      if (h = a.first).is_a? Hash and (type = h.symbolize_keys[self.class.inheritance_column.to_sym]) and (klass = type.to_s.constantize) != self
        raise "Must be a subclass of Badge" unless klass < self  # klass should be a descendant of self
        return klass.new_without_cast(*a, &b)
      end
      raise "Badge must be created through a subclass."
      new_without_cast(*a, &b)
    end
    alias_method_chain :new, :cast
  end
end

Option 2: Patch AssociationReflection to behave more intelligently

class ActiveRecord::Reflection::AssociationReflection
  def build_association(*opts)
    col = klass.inheritance_column.to_sym
    if (h = opts.first).is_a? Hash and (type = h.symbolize_keys
) and type.class == Class opts.first
.to_s.constantize.new(*opts) elsif klass.abstract_class? raise "#{klass.to_s} is an abstract class and can not be directly instantiated" else klass.new(*opts) end end end

My preference is Option 2 even though it might break in future releases of Rails. I’d rather have Rails behaving as expected than pepper my models code with repetitive hacks.

The above solutions were inspired from a couple of different posts and sources.

I submitted Option 2 as a patch for Rails.