<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>XTargets</title>
  <id>http://xtargets.com</id>
  <updated>2010-03-12</updated>
  <author>
    <name>Brad Phelan</name>
  </author>
  <entry>
    <title>Ensuring the selected item in a sencha touch list is always visible.</title>
    <link rel="alternate" href="http://xtargets.com/2012/04/30/ensuring-the-selected-item-in-a-sencha-touch-list-is-always-visible/"/>
    <id>http://xtargets.com/2012/04/30/ensuring-the-selected-item-in-a-sencha-touch-list-is-always-visible/</id>
    <published>2012-04-30</published>
    <updated>2012-04-30</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;Sencha Touch &amp;ldquo;Ext.List&amp;rdquo; lists are nice and flexible but they have one fiddly
problem. If you manually set the selected item in a list from a callback like
so&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;card.on
  activeitemchange: (card, item, oldIndex)=&amp;gt;
    index = card.items.indexOf(item)

    # Change the list selection to reflect
    # the current card
    list.select(index)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;where &lt;strong&gt;list&lt;/strong&gt; is a currently defined &lt;strong&gt;Ext.List&lt;/strong&gt; object then all works fine
until you select an item that is not currently in the visible window.
&lt;strong&gt;Grrrrrr&lt;/strong&gt; it is not visible and there is no public API to help you keep it
so.&lt;/p&gt;

&lt;p&gt;For example my setup is a card layout on the right and a list on the
left reflecting the current card.&lt;/p&gt;

&lt;div class="thumbnail"&gt;&lt;a href="https://skitch.com/bradphelan/8s38m/ios-simulator"&gt;&lt;img style="max-width:638px" src="https://img.skitch.com/20120430-ppxukim7mchmh3buana8pnufec.medium.jpg" alt="iOS Simulator" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span&gt;Uploaded with &lt;a href="http://skitch.com"&gt;Skitch&lt;/a&gt;!&lt;/span&gt;&lt;/div&gt;


&lt;p&gt;To select a card you can either directly select an item from the list or proceed
sequentially back and forth using the left and right arrow on top of
the card&amp;hellip;&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;Sencha Touch &amp;ldquo;Ext.List&amp;rdquo; lists are nice and flexible but they have one fiddly
problem. If you manually set the selected item in a list from a callback like
so&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;card.on
  activeitemchange: (card, item, oldIndex)=&amp;gt;
    index = card.items.indexOf(item)

    # Change the list selection to reflect
    # the current card
    list.select(index)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;where &lt;strong&gt;list&lt;/strong&gt; is a currently defined &lt;strong&gt;Ext.List&lt;/strong&gt; object then all works fine
until you select an item that is not currently in the visible window.
&lt;strong&gt;Grrrrrr&lt;/strong&gt; it is not visible and there is no public API to help you keep it
so.&lt;/p&gt;

&lt;p&gt;For example my setup is a card layout on the right and a list on the
left reflecting the current card.&lt;/p&gt;

&lt;div class="thumbnail"&gt;&lt;a href="https://skitch.com/bradphelan/8s38m/ios-simulator"&gt;&lt;img style="max-width:638px" src="https://img.skitch.com/20120430-ppxukim7mchmh3buana8pnufec.medium.jpg" alt="iOS Simulator" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span&gt;Uploaded with &lt;a href="http://skitch.com"&gt;Skitch&lt;/a&gt;!&lt;/span&gt;&lt;/div&gt;


&lt;p&gt;To select a card you can either directly select an item from the list or proceed
sequentially back and forth using the left and right arrow on top of
the card.&lt;/p&gt;

&lt;p&gt;What we would like is an unobtrusive solution that doesn&amp;rsquo;t jump the scroll
of the list around too much but keeps the selected item always in view and
makes it always possible to directly select a next item on the list without
finger scrolling.&lt;/p&gt;

&lt;p&gt;I have added the following code to my &lt;strong&gt;activeitemchange&lt;/strong&gt; callback. It
can be added anywhere it is appropriate or made a method on a subclass
of &lt;strong&gt;Ext.List&lt;/strong&gt; if you prefer.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;card.on
  activeitemchange: (card, item, oldIndex)=&amp;gt;
    index = card.items.indexOf(item)
    list.select(index)

    # Get the selected item. Seems
    # a bit ugly but it works
    cls = list.getSelectedCls()
    selectedElement = list.element.down("." + cls)
    selectedHeight = selectedElement.getHeight()

    if selectedElement
      # Height of the full list
      fullListHeight = list.element.down(".x-list-container").getHeight()

      # Height of the scroll window
      scrollWindowHeight = list.element.getHeight()

      yTop = selectedElement.dom.offsetTop
      yBottom = yTop + selectedHeight

      scroller = list.getScrollable().getScroller()

      # Outside this zone a scrollTo will be triggered
      triggerZone =
        min: scroller.position.y + selectedHeight
        max: scroller.position.y + scrollWindowHeight - selectedHeight

      # Conditions for items above the current scroll
      # position
      if yTop &amp;lt; triggerZone.min
        pos = yTop - selectedHeight

      # Conditions for items below the current scroll
      # position
      if yBottom &amp;gt; triggerZone.max
        pos = yTop + 2*selectedHeight - scrollWindowHeight

      # Adjust for the edge cases where the item
      # to scroll is at the top or bottom of the
      # list so we don't get nasty jumping effects
      if pos?
        pos = Math.max(0, pos)
        pos = Math.min(pos, fullListHeight - scrollWindowHeight)
        scroller.scrollTo(0,pos,true)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can see a screen cast of the effect in action below&lt;/p&gt;

&lt;iframe src="http://player.vimeo.com/video/41286078" width="500" height="644" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen&gt;&lt;/iframe&gt;

</content>
  </entry>
  <entry>
    <title>Pain free sencha touch 2.0 setup with sinatra and guard</title>
    <link rel="alternate" href="http://xtargets.com/2012/04/29/pain-free-sencha-touch-20-setup-with-sinatra-and-guard/"/>
    <id>http://xtargets.com/2012/04/29/pain-free-sencha-touch-20-setup-with-sinatra-and-guard/</id>
    <published>2012-04-29</published>
    <updated>2012-04-29</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;Setting up a dencent workflow with sencha touch is not too complex especially
if you pull out the ruby toolbelt. I&amp;rsquo;ll show you how to do it and add in
coffeescript for a bonus&amp;hellip;&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;Setting up a dencent workflow with sencha touch is not too complex especially
if you pull out the ruby toolbelt. I&amp;rsquo;ll show you how to do it and add in
coffeescript for a bonus.&lt;/p&gt;

&lt;p&gt;First download the sencha touch packages and install as per instructions. If you
are using ZSH then it probably won&amp;rsquo;t work for you. Add this or similar to your
zshrc&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;export PATH=/Applications/SenchaSDKTools-2.0.0-Beta:$PATH
export PATH=/Applications/SenchaSDKTools-2.0.0-Beta/bin:$PATH
export PATH=/Applications/SenchaSDKTools-2.0.0-Beta/jsbuilder:$PATH
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Create a new sencha project and add it to your favorite version control
system. I use git. I would skip the sdk directory that is auto generated
as it is full of win32 binaries that you may not want clogging your
version control server.&lt;/p&gt;

&lt;p&gt;Now create a Gemfile for use with bundler&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;source 'http://rubygems.org'
gem "sinatra"
group :development do
  gem "compass"
  gem "guard"
  gem "guard-coffeescript"
  gem "guard-compass", :git =&amp;gt; 'git@github.com:bradphelan/guard-compass.git'
  gem "growl"
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Do&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;bundle install
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and all your gems will be installed.&lt;/p&gt;

&lt;p&gt;Sinatra will help us to create a simple web server. No need for apache! Create the
following ruby file call &lt;em&gt;app.rb&lt;/em&gt; in the project root directory.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require 'sinatra'
require "sinatra/reloader" if development?

# Make sure our assets reload on every request.
set :static_cache_control, [:public, :max_age =&amp;gt; 0]

# Pick which set of files get served depending
# on our environment
case ENV["RACK_ENV"] || "development"
when "production"
  puts "Production"
  set :public_folder, "./build/production"
when "testing"
  puts "Production"
  set :public_folder, "./build/testing"
else "development"
  puts "Debug"
  set :public_folder, "./"
end

get "/" do
  redirect "/index.html"
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You will need a rake file for common command like starting the server
and building releases. This is a simple starter to put in file &lt;strong&gt;Rakefile&lt;/strong&gt;
in the project root directory.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;namespace :build do
  desc "Build the production code"
  task :production do
    sh 'sencha app build -e production'
  end

  desc "Build the testing code"
  task :testing do
    sh 'sencha app build -e testing'
  end

end

namespace :serve do

  desc "Run the production code"
  task :production do
    ENV['RACK_ENV']='production'
    sh 'ruby app.rb'
  end

  desc "Run the testing code"
  task :testing do
    ENV['RACK_ENV']='testing'
    sh 'ruby app.rb'
  end

  desc "Run the development code"
  task :development do
    ENV['RACK_ENV']='development'
    sh 'ruby app.rb'
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now you will want to fiddle with the standard CSS of sencha or add your own
custom styles. Sencha uses SASS so that is why we have the compass gem
installed. We will use that next. Create a file called &lt;strong&gt;Guardfile&lt;/strong&gt; in the
project root directory and put this in it&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require 'guard/guard'

guard 'coffeescript' do
  watch %r{^app/.+\.coffee$}
  watch %r{^app.coffee$}
end

config = File.expand_path "../resources/sass/config.rb", __FILE__
path = File.expand_path "../..", config

guard 'compass', :project_path =&amp;gt; path,  :configuration_file =&amp;gt; config do
  watch %r{resources/.+\.scss}
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can then from the command line run&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;bundle exec guard
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and your app.css will always be up to date. There is also a section in
my guard file for compiling my coffeescript to javascript. Coffeescript
is a great alternative to javascript and works perfectly with Sencha.&lt;/p&gt;

&lt;p&gt;Now to start your server you just do&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;rake server:development
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and you will see something like&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;rake serve:production (in /Users/bradphelan/workspace/xxxxx)
ruby app.rb
Production
[2012-04-29 21:44:04] INFO  WEBrick 1.3.1
[2012-04-29 21:44:04] INFO  ruby 1.9.2 (2011-02-18) [x86_64-darwin10.8.0]
== Sinatra/1.3.2 has taken the stage on 4567 for production with backup from WEBrick
[2012-04-29 21:44:04] INFO  WEBrick::HTTPServer#start: pid=84278 port=4567
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and you can point your browser / iDevice / fondlePad / android thingie at&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;http://localhost:4567/index.html
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and your app is served. And now you have a sinatra backend you can add
custom routes to do backend processing of the sencha data stores. If
you are interested in me writing a post on how to do that then tweet
me and I&amp;rsquo;ll write that up next.&lt;/p&gt;

&lt;p&gt;And to to build your production release which packages all your
js code into a single minified file do&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;rake build:production
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That package in &lt;strong&gt;app/build/production&lt;/strong&gt; is what is served when
you start the server in production mode and is the default when
served from somewhere like heroku.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Solving polymorphic has_one through building and nested forms</title>
    <link rel="alternate" href="http://xtargets.com/2012/04/04/solving-polymorphic-hasone-through-building-and-nested-forms/"/>
    <id>http://xtargets.com/2012/04/04/solving-polymorphic-hasone-through-building-and-nested-forms/</id>
    <published>2012-04-04</published>
    <updated>2012-04-04</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;I recently hit on the brilliant idea of using &lt;strong&gt;STI&lt;/strong&gt; (single table inheritence),
&lt;strong&gt;polymorphic classes&lt;/strong&gt;, &lt;strong&gt;nested forms&lt;/strong&gt; and &lt;strong&gt;has_one through&lt;/strong&gt; models all at once just
to prove how silly I am.&lt;/p&gt;

&lt;p&gt;My use case is an asset manager backed by paperclip. I wanted all assets
to go into a single S3 folder and be mananged by a single :assets table.
Then I wanted &lt;strong&gt;any&lt;/strong&gt; other model to be able to associate uploaded assets
at any arity. Gumpf!&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;I recently hit on the brilliant idea of using &lt;strong&gt;STI&lt;/strong&gt; (single table inheritence),
&lt;strong&gt;polymorphic classes&lt;/strong&gt;, &lt;strong&gt;nested forms&lt;/strong&gt; and &lt;strong&gt;has_one through&lt;/strong&gt; models all at once just
to prove how silly I am.&lt;/p&gt;

&lt;p&gt;My use case is an asset manager backed by paperclip. I wanted all assets
to go into a single S3 folder and be mananged by a single :assets table.
Then I wanted &lt;strong&gt;any&lt;/strong&gt; other model to be able to associate uploaded assets
at any arity. Gumpf!&lt;/p&gt;

&lt;p&gt;My base class for an STI compliant asset table is&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# == Schema Information
#
# Table name: assets
#
#  id                      :integer         not null, primary key
#  attachment_file_name    :string(255)
#  attachment_content_type :string(255)
#  attachment_file_size    :integer
#  attachment_updated_at   :datetime
#  created_at              :datetime        not null
#  updated_at              :datetime        not null
#  type                    :string(255)
#  attachment_processing   :boolean
#  terminated              :boolean         default(FALSE)
#

    class Asset &amp;lt; ActiveRecord::Base
        belongs_to :assetable, :polymorphic =&amp;gt; true
        delegate :url, :to =&amp;gt; :attachment
        delegate :expiring_url, :to =&amp;gt; :attachment
        delegate :present?, :to =&amp;gt; :attachment

        validates_attachment_presence :attachment

        has_many :assetable_assets, :dependent =&amp;gt; :destroy
        has_many :assetables, :through =&amp;gt; :assetable_assets, :as =&amp;gt; :assetable

        AssetPath = ":rails_env/assets/:id/:style.:extension"

        def self.configure_attachment options = {}
            options.merge! :path =&amp;gt; AssetPath
            has_attached_file :attachment, options
        end

    end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then I need a class to associate other objects, &lt;strong&gt;assetables&lt;/strong&gt;, with uploaded
assets. Note that &lt;strong&gt;assetables&lt;/strong&gt; are polymorphic&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    # == Schema Information
    #
    # Table name: assetable_assets
    #
    #  id             :integer         not null, primary key
    #  assetable_id   :integer
    #  assetable_type :string(255)
    #  asset_id       :integer
    #  created_at     :datetime        not null
    #  updated_at     :datetime        not null
    #

    class AssetableAsset &amp;lt; ActiveRecord::Base
        belongs_to :assetable, :polymorphic =&amp;gt; true
        belongs_to :asset

        # Clean up orphans
        before_destroy do
            if not asset.nil?
                if asset.assetable_assets.count == 1
                    asset.background_destroy
                end
            end
        end
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And an example of a concrete &lt;strong&gt;assetable&lt;/strong&gt; class.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# == Schema Information
#
# Table name: users
#
#  id                     :integer         not null, primary key
#  email                  :string(255)     default(""), not null
#

class User &amp;lt; ActiveRecord::Base

    has_one :assetable_asset, :as =&amp;gt; :assetable, :dependent =&amp;gt; :destroy
    has_one :avatar, :source =&amp;gt; :asset, :through =&amp;gt; :assetable_asset, :class_name =&amp;gt; "ImageAsset"
    attr_accessible :avatar_attributes
    accepts_nested_attributes_for :avatar

    def build_avatar attributes={}, opts={}
        asset = ::ImageAsset.new attributes, opts
        build_assetable_asset :asset =&amp;gt; asset
        self.avatar = asset
    end

    def avatar_with_build
        a = avatar_without_build
        unless a
            return build_avatar
        end
        a
    end
    alias_method_chain :avatar, :build
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now I can upload an avatar via a formtastic form as so&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;= semantic_form_for @user, :url =&amp;gt; user_profile_path(@user), :html =&amp;gt; { :multipart =&amp;gt; true } do |f|
        = f.inputs do 
            .span5
                = f.input :email
                = f.input :name

                - if user.avater.present?
                    = image_tag user.avatar.url(:thumb)

                = f.inputs :attachment, :for =&amp;gt; :avatar do |a|
                    = a.input :attachment, :as =&amp;gt; :file
        = f.buttons
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For some reason that I can&amp;rsquo;t get my head around Rails doesn&amp;rsquo;t ship
with a handler for polymorphic has_one builders. I expected to be
able to do&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    user.build_avatar
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;out of the box but I got an error that the method does not exist and
it took some fiddling to figure out how to emulate it.&lt;/p&gt;

&lt;p&gt;For reference, The image asset class is defined below which fleshes
out the STI part of the problem. Maybe it would not be necessary to
have STI support on the assets table but it might happen that I
have assets with different styles and need to classify them
as such.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class ImageAsset &amp;lt; Asset

    configure_attachment styles: ImageSizes.standard_sizes_hash

    validates_attachment_content_type :attachment, 
        :content_type =&amp;gt; %r{image/.*}, 
        :less_than =&amp;gt; 5.megabyte

end
&lt;/code&gt;&lt;/pre&gt;
</content>
  </entry>
  <entry>
    <title>Simple javascript powered inline confirm</title>
    <link rel="alternate" href="http://xtargets.com/2012/03/29/simple-javascript-powered-inline-confirm/"/>
    <id>http://xtargets.com/2012/03/29/simple-javascript-powered-inline-confirm/</id>
    <published>2012-03-29</published>
    <updated>2012-03-29</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;Browser confirmation dialogs are ugly. They can&amp;rsquo;t really be styled
and anyway who wants a big fat popup making the user drive thier mouse
and focus away from where the action is at. Here is an easy solution
using unobtrusive javascript techniques&lt;/p&gt;

&lt;p&gt;Say we have an image viewer and we want a link to delete the image.
My haml might look like&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;.item{'data-image_id'=&amp;gt;image.id}
  = image_tag image.attachment.expiring_url(s3_expiry, :large)
    .carousel-caption

      = link_to url_for_event(:delete_image, :asset_id =&amp;gt; image.id),
        :method =&amp;gt; :delete, 
        :remote =&amp;gt; true,
        :class =&amp;gt; "delete inline-confirm" do
        delete
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Forget the fluff. I&amp;rsquo;m using twitter bootstrap carousel here but that
is irrelevant. The key is adding the class &lt;strong&gt;inline-confirm&lt;/strong&gt;. That
is all.&lt;/p&gt;

&lt;p&gt;The user interface interaction will go like this&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;IMG

delete
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Imagine IMG is replaced with a picture of your sweetheart. You then
click on &lt;strong&gt;delete&lt;/strong&gt; and the screen changes to&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;IMG

yes no
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You click on &lt;strong&gt;yes&lt;/strong&gt; and the original link is followed. You click on &lt;strong&gt;no&lt;/strong&gt;
and the action canceled. The coffeescript to achieve this is&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$(document).ready =&amp;gt;

  $("body").on "click", ".inline-confirm", (e)=&amp;gt;
    t = $(e.target)
    t.hide()

    yn = """
      &amp;lt;div&amp;gt;
        &amp;lt;a class="no" href='#' &amp;gt;no&amp;lt;/a&amp;gt;
        &amp;amp;nbsp;
        &amp;lt;a class="yes" href='#'&amp;gt;yes&amp;lt;/a&amp;gt;
      &amp;lt;/div&amp;gt;
    """
    yn = $(yn)

    yn = yn.insertAfter t
    yn.fadeIn()

    yn.find(".yes").one "click", =&amp;gt;
      t.removeClass("inline-confirm")
      t.click()
      t.addClass("inline-confirm")
      yn.remove()
      false

    yn.find(".no").one "click", =&amp;gt;
      yn.remove()
      t.show()
      false

    false
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The user experience improvement was immediate. To delete a sequence of images could be done
an order of magnitude faster because I didn&amp;rsquo;t have to move the mouse around.&lt;/p&gt;

&lt;p&gt;The code could be enhanced with more features and maybe some styling. If you have ideas
for enhancements tweet me&amp;hellip;&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;Browser confirmation dialogs are ugly. They can&amp;rsquo;t really be styled
and anyway who wants a big fat popup making the user drive thier mouse
and focus away from where the action is at. Here is an easy solution
using unobtrusive javascript techniques&lt;/p&gt;

&lt;p&gt;Say we have an image viewer and we want a link to delete the image.
My haml might look like&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;.item{'data-image_id'=&amp;gt;image.id}
  = image_tag image.attachment.expiring_url(s3_expiry, :large)
    .carousel-caption

      = link_to url_for_event(:delete_image, :asset_id =&amp;gt; image.id),
        :method =&amp;gt; :delete, 
        :remote =&amp;gt; true,
        :class =&amp;gt; "delete inline-confirm" do
        delete
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Forget the fluff. I&amp;rsquo;m using twitter bootstrap carousel here but that
is irrelevant. The key is adding the class &lt;strong&gt;inline-confirm&lt;/strong&gt;. That
is all.&lt;/p&gt;

&lt;p&gt;The user interface interaction will go like this&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;IMG

delete
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Imagine IMG is replaced with a picture of your sweetheart. You then
click on &lt;strong&gt;delete&lt;/strong&gt; and the screen changes to&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;IMG

yes no
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You click on &lt;strong&gt;yes&lt;/strong&gt; and the original link is followed. You click on &lt;strong&gt;no&lt;/strong&gt;
and the action canceled. The coffeescript to achieve this is&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$(document).ready =&amp;gt;

  $("body").on "click", ".inline-confirm", (e)=&amp;gt;
    t = $(e.target)
    t.hide()

    yn = """
      &amp;lt;div&amp;gt;
        &amp;lt;a class="no" href='#' &amp;gt;no&amp;lt;/a&amp;gt;
        &amp;amp;nbsp;
        &amp;lt;a class="yes" href='#'&amp;gt;yes&amp;lt;/a&amp;gt;
      &amp;lt;/div&amp;gt;
    """
    yn = $(yn)

    yn = yn.insertAfter t
    yn.fadeIn()

    yn.find(".yes").one "click", =&amp;gt;
      t.removeClass("inline-confirm")
      t.click()
      t.addClass("inline-confirm")
      yn.remove()
      false

    yn.find(".no").one "click", =&amp;gt;
      yn.remove()
      t.show()
      false

    false
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The user experience improvement was immediate. To delete a sequence of images could be done
an order of magnitude faster because I didn&amp;rsquo;t have to move the mouse around.&lt;/p&gt;

&lt;p&gt;The code could be enhanced with more features and maybe some styling. If you have ideas
for enhancements tweet me.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Understanding and solving race conditions with ruby rails and background workers</title>
    <link rel="alternate" href="http://xtargets.com/2012/03/08/understanding-and-solving-race-conditions-with-ruby-rails-and-background-workers/"/>
    <id>http://xtargets.com/2012/03/08/understanding-and-solving-race-conditions-with-ruby-rails-and-background-workers/</id>
    <published>2012-03-08</published>
    <updated>2012-03-08</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;Once upon a time you wrote a web application where a request would come in, you
would process the request and send the result to the client. Job done. These days
it is a little more complex. The jobs that a request may invoke may take longer
than the client is willing to wait for a browser response so we add jobs to a
job queue.&lt;/p&gt;

&lt;p&gt;Sending an email is the cannonical example. A client performs some action in
the browser which invokes a response from the server. Part of that response
may be to send an email. However if we wait till the email is sent before
we respond to the browser it may take a long time and result in a grumpy
client.&lt;/p&gt;

&lt;p&gt;Background workers to the rescue! Almost&amp;hellip;&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;Once upon a time you wrote a web application where a request would come in, you
would process the request and send the result to the client. Job done. These days
it is a little more complex. The jobs that a request may invoke may take longer
than the client is willing to wait for a browser response so we add jobs to a
job queue.&lt;/p&gt;

&lt;p&gt;Sending an email is the cannonical example. A client performs some action in
the browser which invokes a response from the server. Part of that response
may be to send an email. However if we wait till the email is sent before
we respond to the browser it may take a long time and result in a grumpy
client.&lt;/p&gt;

&lt;p&gt;Background workers to the rescue! Almost.&lt;/p&gt;

&lt;p&gt;Now if your background workers feed from a job queue in the same database as
your models, &lt;a href="https://github.com/tobi/delayed_job"&gt;Delayed Job&lt;/a&gt; being an
example of this, then you have not much to worry about and you can stop
reading.&lt;/p&gt;

&lt;p&gt;However if you are using &lt;a href="https://github.com/mperham/girl_friday"&gt;Girl Friday&lt;/a&gt;
which is memory/actor based or or &lt;a href="https://github.com/defunkt/resque"&gt;Resque&lt;/a&gt;
which is Redis based or any other queuing mechanism which is not based on
ActiveRecord and resident in the same db as your models you are in for a scary
ride of race conditions unless you are very very careful.&lt;/p&gt;

&lt;p&gt;Picture the following controller&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class FooController &amp;lt; ActionController::Base

  respond_to :html

  def create

    @foo = Foo.new params[:foo]
    @foo.save

    mail_subscribers_with @foo.id

    respond_with @foo

  end

end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Our imaginary mail_subscribers_with method might use Girl Friday as it&amp;rsquo;s
job mechanism so we define it like&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def mail_subscribers_with id

   MAIL_SUBSCRIBERS_QUEUE.push :id =&amp;gt; id

end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and the queue is defined in config/initializers/girl_friday.rb&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;MAIL_SUBSCRIBERS_QUEUE = GirlFriday::WorkQueue.new :mail_subscribers_queue, :size =&amp;gt; 3 do |info|

  foo = Foo.find info[:id]

  # A custom ActionMailer class to send the email
  SubscriberMailer.mail(foo).deliver

end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The problem with this is that the queue can be too quick. Each controller
action is wrapped in a transaction in rails. Even though it &lt;strong&gt;seems&lt;/strong&gt; that we
have saved the object to the db before we add the job to the queue this is
misleading. Transactions are local to the current thread in Rails. On another
thread in another transaction the new object will not appear until the first
transaction is commited.&lt;/p&gt;

&lt;p&gt;The end effect is that&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Foo.find info[:id]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;may turn up no record or it may turn up a record. Not a good thing. Race
conditions suck.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/grosser/ar_after_transaction"&gt;After Transaction Gem&lt;/a&gt; to
the rescue.&lt;/p&gt;

&lt;p&gt;This gem allows you to delay a block of code until after the current
transaction is complete and thus everything that will be is commited
to the database. To use it we modify our &lt;strong&gt;mail_subscribers_queue&lt;/strong&gt;
method to be&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def mail_subscribers_with id
   ActiveRecord::Base.after_transaction do
     MAIL_SUBSCRIBERS_QUEUE.push :id =&amp;gt; id
   end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now by the time the&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Foo.find info[:id]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;call is made in the work the object is garunteed to exist. The astute
reader will note the Rails 3 &lt;strong&gt;after_commit&lt;/strong&gt; performs a similar function
but after_transaction is more flexible and can be used inline
with other source code making the intention of the code more obvious.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Caching signed uris with Paperclip and Amazon S3</title>
    <link rel="alternate" href="http://xtargets.com/2012/03/08/caching-signed-uris-with-paperclip-and-amazon-s3/"/>
    <id>http://xtargets.com/2012/03/08/caching-signed-uris-with-paperclip-and-amazon-s3/</id>
    <published>2012-03-08</published>
    <updated>2012-03-08</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;With paperclip we can specify that a generated URL will
expire in a certain period of time. The simple way to do
this is just&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;user.avatar.expiring_url(24.hours, :thumb)
&lt;/code&gt;&lt;/pre&gt;
</summary>
    <content type="html">&lt;p&gt;With paperclip we can specify that a generated URL will
expire in a certain period of time. The simple way to do
this is just&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;user.avatar.expiring_url(24.hours, :thumb)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The bad thing about the above is that it generates a new
url on every call and every time the user refreshes the
page they get new image urls. The browser doesn&amp;rsquo;t get
the chance to cache the page and your S3 bandwidth bill
goes up.&lt;/p&gt;

&lt;p&gt;The better way is to use an explicit date for the expiry.&lt;/p&gt;

&lt;p&gt;If you would like your images to expire after a &lt;strong&gt;maximum&lt;/strong&gt;
of 25 hours then create a method like below in your application
helpers file&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def s3_expiry
      Time.zone.now.beginning_of_day.since 25.hours
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then you can do&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;user.avatar.expiring_url(s3_expiry, :thumb)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The image url will expire at 1am in the morning tomorrow nomatter
how many time time you regenerate the url. This means the url
stays stable and is suitable for browser caching for
25 hours. However at a maximum of 24 hours new URL&amp;rsquo;s are generated
leaving a minimum cache window of 1 hour and and average of 12.5
hours of caching.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Testing OAuth 2.0 apps locally</title>
    <link rel="alternate" href="http://xtargets.com/2012/03/05/testing-oauth-20-apps-locally/"/>
    <id>http://xtargets.com/2012/03/05/testing-oauth-20-apps-locally/</id>
    <published>2012-03-05</published>
    <updated>2012-03-05</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;In your facebook app setup do&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;App Domain =&amp;gt; mydomain.com
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;in your /etc/hosts&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;127.0.0.1 localhost.mydomain.com
::= localhost.mydomain.com
&lt;/code&gt;&lt;/pre&gt;
</summary>
    <content type="html">&lt;p&gt;In your facebook app setup do&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;App Domain =&amp;gt; mydomain.com
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;in your /etc/hosts&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;127.0.0.1 localhost.mydomain.com
::= localhost.mydomain.com
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;in a shell script&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/sh
sudo ssh -L 80:localhost:3000 -l `whoami` -N localhost
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When this script is run then it will block. Press ^C to stop
the port forwarding. This could be made into a rake task if
you like&lt;/p&gt;

&lt;p&gt;What the above does is tell facebook to authorize an application operating at
the *.mydomain.com uri pattern. In our /etc/hosts we map localhost.mydomain.com
to the loopback device and in the shell script we forward port 80 to the real
port our rails app runs on. Last of all we need to configure OAuth in our
OmniAuth in our rails app to use the correct end points depending on our
environment.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if Rails.env.production?
  OmniAuth.config.full_host = "http://mydomain.com"
elsif Rails.env.test?
  OmniAuth.config.full_host = "http://staging.mydomain.com"
elsif Rails.env.development?
  OmniAuth.config.full_host = "http://localhost.mydomain.com"
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you are using http rather than https then change the http to http above.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Using with_scope and ActiveRecord extension to set join model attributes</title>
    <link rel="alternate" href="http://xtargets.com/2012/02/29/using-withscope-and-activerecord-extension-to-set-join-model-attributes/"/>
    <id>http://xtargets.com/2012/02/29/using-withscope-and-activerecord-extension-to-set-join-model-attributes/</id>
    <published>2012-02-29</published>
    <updated>2012-02-29</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;I have the following&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class User &amp;lt; ActiveRecord::Base
  has_many :user_venue_managements, :dependent =&amp;gt; :destroy

  has_many :venues, :through =&amp;gt; :user_venue_managements do
&lt;/code&gt;&lt;/pre&gt;
</summary>
    <content type="html">&lt;p&gt;I have the following&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class User &amp;lt; ActiveRecord::Base
  has_many :user_venue_managements, :dependent =&amp;gt; :destroy

  has_many :venues, :through =&amp;gt; :user_venue_managements do
    def create *params, &amp;amp;block
      UserVenueManagement.with_scope :create =&amp;gt; { :role =&amp;gt; :owner } do
        super *params, &amp;amp;block
      end
    end
    def create! *params, &amp;amp;block
      UserVenueManagement.with_scope :create =&amp;gt; { :role =&amp;gt; :owner } do
        super *params, &amp;amp;block
      end
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I can now do&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;u = User.first
u.venues.create! :address =&amp;gt; "New York"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;will create me a venue with the correct role set on the join model. Executed
SQL is&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;INSERT INTO "venues" ("address") VALUES (?)  [["address", "New York]]
INSERT INTO "user_venue_managements" ("role", "user_id", "venue_id") VALUES (?, ?, ?)  
   [["role", :owner], ["user_id", 1], ["venue_id", 148]]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I&amp;rsquo;m a little unhappy with the duplicate create and create! repititon but it
works.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>RSpec steps for cleaner specs</title>
    <link rel="alternate" href="http://xtargets.com/2012/02/25/rspec-steps-for-cleaner-specs/"/>
    <id>http://xtargets.com/2012/02/25/rspec-steps-for-cleaner-specs/</id>
    <published>2012-02-25</published>
    <updated>2012-02-25</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;The following RSpec idiom drives me nuts in my unit tests.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;describe Invitation do
  before do 
    @owner = Factory :registered_user
    @guest = Factory :user
    @event = Factory :event, :owner =&amp;gt; @owner
    GirlFriday::WorkQueue.immediate!
  end
  describe "Comment subscriptions" do
    describe "A new invitation" do
      before do
        @invitation = @event.invite @guest
      end

      it "should not be subscribed to comments" do
        @invitation.should_not be_subscribed_for_comments
      end

      describe "After a comment has been made" do
        before do
          @comment = Comment.build_from(@event, @guest.id, "foo")
          @comment.save!
        end

        it "should be subscribed to comments" do 
          @invitation.reload
          @invitation.should be_subscribed_for_comments
        end
      end
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Yeah I know. No stubbing, mocks or other fancy cool stuff. However there is so
much boiler plate to describe what is really just a sequence of steps to verify.
The rspec output is ( and the wording could be better but this is not the point )&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Comment subscriptions
  A new invitation
    should not be subscribed to comments
    After a comment has been made
      should be subscribed to comments
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Why all the indentation. It&amp;rsquo;s a sequence of steps we are verifying the
behaviour of, not generating a YAML file!&amp;hellip;&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;The following RSpec idiom drives me nuts in my unit tests.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;describe Invitation do
  before do 
    @owner = Factory :registered_user
    @guest = Factory :user
    @event = Factory :event, :owner =&amp;gt; @owner
    GirlFriday::WorkQueue.immediate!
  end
  describe "Comment subscriptions" do
    describe "A new invitation" do
      before do
        @invitation = @event.invite @guest
      end

      it "should not be subscribed to comments" do
        @invitation.should_not be_subscribed_for_comments
      end

      describe "After a comment has been made" do
        before do
          @comment = Comment.build_from(@event, @guest.id, "foo")
          @comment.save!
        end

        it "should be subscribed to comments" do 
          @invitation.reload
          @invitation.should be_subscribed_for_comments
        end
      end
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Yeah I know. No stubbing, mocks or other fancy cool stuff. However there is so
much boiler plate to describe what is really just a sequence of steps to verify.
The rspec output is ( and the wording could be better but this is not the point )&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Comment subscriptions
  A new invitation
    should not be subscribed to comments
    After a comment has been made
      should be subscribed to comments
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Why all the indentation. It&amp;rsquo;s a sequence of steps we are verifying the
behaviour of, not generating a YAML file!.&lt;/p&gt;

&lt;p&gt;I&amp;rsquo;ve been using &lt;a href="https://github.com/railsware/rspec-example_steps"&gt;RSpec Example Steps&lt;/a&gt; in my acceptence tests recently and I
thought why not give it a try for normal RSpec tests and see what happens.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;describe Invitation do
  Steps do
    Given "A user a guest and an event" do
      @owner = Factory :registered_user
      @guest = Factory :user
      @event = Factory :event, :owner =&amp;gt; @owner
      GirlFriday::WorkQueue.immediate!
    end

    When "the guest is invited to the event" do
      @invitation = @event.invite @guest
    end

    Then "the guest should not yet be subscribed to comments" do
      @invitation.should_not be_subscribed_for_comments
    end

    When "the guest makes a comment" do
      @comment = Comment.build_from(@event, @guest.id, "foo")
      @comment.save!
    end

    Then "the guest should be subscribed to comments" do
      @invitation.reload
      @invitation.should be_subscribed_for_comments
    end
  end

end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;with the RSpec output being&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Given A user a guest and an event
When the guest is invited to the event
Then the guest should not yet be subscribed to comments
When the guest makes a comment
Then the guest should be subscribed to comments
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Why would you want to write your specs as if you are some asynchronous
coding god. If you want to test a sequence of steps and have a nice
RSpec report that describes the behaviour of the code then try out
&lt;a href="https://github.com/railsware/rspec-example_steps"&gt;RSpec Example Steps&lt;/a&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>CANCAN Devise and Apotomo living together in harmony</title>
    <link rel="alternate" href="http://xtargets.com/2012/02/14/cancan-devise-and-apotomo-living-together-in-harmony/"/>
    <id>http://xtargets.com/2012/02/14/cancan-devise-and-apotomo-living-together-in-harmony/</id>
    <published>2012-02-14</published>
    <updated>2012-02-14</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;The &lt;a href="https://github.com/apotonick/apotomo"&gt;Apotomo Framework&lt;/a&gt; cleans up Ruby On
Rails view code. It encapsulates &lt;strong&gt;widgets&lt;/strong&gt; into easy to reuse object oriented
modules packages. However none of the examples I could find used real world
examples with authorization and authentication bundled in.&lt;/p&gt;

&lt;p&gt;The packages I use are &lt;a href="https://github.com/plataformatec/devise"&gt;Devise&lt;/a&gt; and
&lt;a href="https://github.com/ryanb/cancan"&gt;CANCAN&lt;/a&gt; which seem to be pretty much standard
with most new rails projects&lt;/p&gt;

&lt;p&gt;The easy way to get it working is to create a base class which adds in all the functionality
for auth that you will need.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class AuthorizableWidget &amp;lt; Apotomo::Widget

  include Devise::Controllers::Helpers 
  helper_method :current_user

  def can?(action, object)
    current_ability.can? action, object
  end
  helper_method :can?

  def cannot?(action, object)
    current_ability.cannot? action, object
  end
  helper_method :cannot?

  def authorize! *args
    parent_controller.authorize! *args
  end

  def current_ability
    ::Ability.new current_user
  end

end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that above I am calling the &lt;strong&gt;authorize!&lt;/strong&gt; method on the parent_controller which
is the &lt;em&gt;real&lt;/em&gt; controller that the browser calls. The controller.authorize! method sets
a variable on the controller which sets a flag telling the controller that an &lt;strong&gt;authorize!&lt;/strong&gt;
method has been called. If you use the method &lt;strong&gt;check_authorization&lt;/strong&gt; as a sanity check
this flag is what stops the error being thrown.&lt;/p&gt;

&lt;p&gt;This becomes the base class for all new widgets that need authorization capabilities. You
use it so&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;The &lt;a href="https://github.com/apotonick/apotomo"&gt;Apotomo Framework&lt;/a&gt; cleans up Ruby On
Rails view code. It encapsulates &lt;strong&gt;widgets&lt;/strong&gt; into easy to reuse object oriented
modules packages. However none of the examples I could find used real world
examples with authorization and authentication bundled in.&lt;/p&gt;

&lt;p&gt;The packages I use are &lt;a href="https://github.com/plataformatec/devise"&gt;Devise&lt;/a&gt; and
&lt;a href="https://github.com/ryanb/cancan"&gt;CANCAN&lt;/a&gt; which seem to be pretty much standard
with most new rails projects&lt;/p&gt;

&lt;p&gt;The easy way to get it working is to create a base class which adds in all the functionality
for auth that you will need.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class AuthorizableWidget &amp;lt; Apotomo::Widget

  include Devise::Controllers::Helpers 
  helper_method :current_user

  def can?(action, object)
    current_ability.can? action, object
  end
  helper_method :can?

  def cannot?(action, object)
    current_ability.cannot? action, object
  end
  helper_method :cannot?

  def authorize! *args
    parent_controller.authorize! *args
  end

  def current_ability
    ::Ability.new current_user
  end

end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that above I am calling the &lt;strong&gt;authorize!&lt;/strong&gt; method on the parent_controller which
is the &lt;em&gt;real&lt;/em&gt; controller that the browser calls. The controller.authorize! method sets
a variable on the controller which sets a flag telling the controller that an &lt;strong&gt;authorize!&lt;/strong&gt;
method has been called. If you use the method &lt;strong&gt;check_authorization&lt;/strong&gt; as a sanity check
this flag is what stops the error being thrown.&lt;/p&gt;

&lt;p&gt;This becomes the base class for all new widgets that need authorization capabilities. You
use it so&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class CommentsWidget &amp;lt; OpenKitchen::AuthorizableWidget

  responds_to_event :comment
  responds_to_event :destroy

  #
  # Events
  #

  # Destroy a comment
  def destroy(evt)
    @comment = Comment.find params[:comment_id]
    @event = @comment.commentable

    # Call the CANCAN authorize! method here!
    authorize! :destroy, @comment

    @comment.destroy
    update({:state =&amp;gt; :display}, @event)
  end

  # Add a comment
  def comment(evt)
    commentable_type = case params[:comment][:commentable_type]
                        when 'Event'
                          ::Event
                        else
                          raise "nice try!"
                        end

    @event = commentable_type.find(params[:comment][:commentable_id])

    @comment = Comment.build_from @event, 
      current_user.id, 
      params[:comment][:body]

    # Call the CANCAN authorize! method here!
    authorize! :create, @comment

    @comment.save


    update({:state =&amp;gt; :display}, @event)
  end

  #
  # Views
  #
  def display(event = options[:event])
    @event = event
    @comments = @event.root_comments
    render
  end

  def list(comments)
    render locals: { comments: comments}
  end

  def item(comment)
    render locals: { comment: comment }
  end

end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that the helpers are also now available to the Apotomo views&lt;/p&gt;

&lt;p&gt;&lt;em&gt;app/widgets/comments/item.html.haml&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;%li.comment{id: "comment_#{comment.id}"}
  %span.author=comment.user.name
  %span.body=simple_format h(comment.body)
  %small
    %span.date
      =distance_of_time_in_words_to_now comment.created_at, true
      ago
  - if can? :destroy, comment
    = link_to url_for_event(:destroy, :comment_id =&amp;gt; comment.id),
      remote: true, 
      class: "destroy", 
      title: t('comment.remove'), 
      :confirm =&amp;gt; t('confirm') do
      %small
        %i.icon-fire
        =t :delete
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It would be nice if this was distributed with Apotomo by default as it was a
bit of trouble to figure out, especially the special flag set by authorize! as
I was initially just calling &lt;strong&gt;current_ability.authorize!&lt;/strong&gt; which didn&amp;rsquo;t set
the flag.&lt;/p&gt;
</content>
  </entry>
</feed>

