less asking, more telling

Jared Carroll

Getting sick of writing the following?

def create
  @user = User.new params[:user]
  if @user.save
    redirect_to @user
  else
    render :action => :new
  end
end

def update
  @user = User.find params[:id]
  if @user.update_attributes params[:user]
    redirect_to @user
  else
    render :action => :edit
  end
end

All this asking doesnt feel very OO. Objects should just know what to do.

But of course we don’t want our models knowing about the UI. So how do we create a dependency from our model to our view in a view-independent way? Let’s try simple events and procs. The only dependency will be that the observer/listener understands #call.

def create
  @user = User.new params[:user]
  @user.after_save_success do
    redirect_to @user
  end
  @user.after_save_failure do
    render :action => :new
  end
  @user.save
end

def update
  @user = User.find params[:id]
  @user.after_update_success do
    redirect_to @user
  end
  @user.after_update_failure do
    render :action => :edit
  end
  @user.update_attributes params[:user]
end

Here I added some more events to ActiveRecord::Base. They’re pretty self-explanatory but the names do suck.

The one thing that is different from normal AR callbacks is that these callbacks are instance specific. They should only apply to that individual user object and not all User instances. Instance specific callbacks are more in the style of prototype based OO instead of traditional class based OO.

Jared Carroll
Sign up to receive a weekly recap from GIANT ROBOTS