<?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>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>
  <entry>
    <title>Autofill timezone selects with the browser timezone</title>
    <link rel="alternate" href="http://xtargets.com/2012/02/09/autofill-timezone-selects-with-the-browser-timezone/"/>
    <id>http://xtargets.com/2012/02/09/autofill-timezone-selects-with-the-browser-timezone/</id>
    <published>2012-02-09</published>
    <updated>2012-02-09</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;Setting timezones in forms is a drag. Making it a little easier on the user lowers
the friction in your website and makes it more likely users will &lt;strong&gt;stick&lt;/strong&gt;. Here
is a simple technique for autofilling timezone selects using formtastic and a little
coffeescript / jquery.&lt;/p&gt;

&lt;p&gt;First create yourself a timezone class and a method for generating a mapping
table between timezone offsets and the name of the timezone as used by rails.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class OpenKitchen
  class TimeZone
    # Returns a hash with javascript compatible timezone
    # offset  as key.
    def self.timezones_by_offset
      @timezone_by_offset = {}
      ActiveSupport::TimeZone.all.each do |tz|
        unless @timezone_by_offset.has_key? tz.utc_offset
          @timezone_by_offset[tz.utc_offset/60] = tz.name
        end
      end
      @timezone_by_offset
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;then create a coffeescript file named&lt;/p&gt;

&lt;p&gt;  /app/assets/javascripts/timezone.js.coffee.erb&lt;/p&gt;

&lt;p&gt;Note the &lt;strong&gt;erb&lt;/strong&gt; ending. This is very important because we are going
to generate the coffeescript code using the above OpenKitchen::TimeZone
class as a helper&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;%  require_dependency 'openkitchen/timezone' %&amp;gt;

class Timezone

  # Table of timezones ( Generated by OpenKitchen::TimeZone class )
  @table: &amp;lt;%= OpenKitchen::TimeZone::timezones_by_offset.to_json %&amp;gt;

  # Find first entry with matching timezone offset
  @lookup_by_offset: (_offset)-&amp;gt;
    _offset =  _offset.toString()
    (tz for offset, tz of @table when _offset == offset)[0]

  # Return the guessed timezone for this browser
  @timezone: -&amp;gt;
    x = new Date
    @lookup_by_offset(-x.getTimezoneOffset())

$(document).ready =&amp;gt;

  # Find timezone selected marked for autofill
  tz_select = $(".time_zone select")
  $("select.timezone.autofill").val(Timezone.timezone())
&lt;/code&gt;&lt;/pre&gt;
</summary>
    <content type="html">&lt;p&gt;Setting timezones in forms is a drag. Making it a little easier on the user lowers
the friction in your website and makes it more likely users will &lt;strong&gt;stick&lt;/strong&gt;. Here
is a simple technique for autofilling timezone selects using formtastic and a little
coffeescript / jquery.&lt;/p&gt;

&lt;p&gt;First create yourself a timezone class and a method for generating a mapping
table between timezone offsets and the name of the timezone as used by rails.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class OpenKitchen
  class TimeZone
    # Returns a hash with javascript compatible timezone
    # offset  as key.
    def self.timezones_by_offset
      @timezone_by_offset = {}
      ActiveSupport::TimeZone.all.each do |tz|
        unless @timezone_by_offset.has_key? tz.utc_offset
          @timezone_by_offset[tz.utc_offset/60] = tz.name
        end
      end
      @timezone_by_offset
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;then create a coffeescript file named&lt;/p&gt;

&lt;p&gt;  /app/assets/javascripts/timezone.js.coffee.erb&lt;/p&gt;

&lt;p&gt;Note the &lt;strong&gt;erb&lt;/strong&gt; ending. This is very important because we are going
to generate the coffeescript code using the above OpenKitchen::TimeZone
class as a helper&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;%  require_dependency 'openkitchen/timezone' %&amp;gt;

class Timezone

  # Table of timezones ( Generated by OpenKitchen::TimeZone class )
  @table: &amp;lt;%= OpenKitchen::TimeZone::timezones_by_offset.to_json %&amp;gt;

  # Find first entry with matching timezone offset
  @lookup_by_offset: (_offset)-&amp;gt;
    _offset =  _offset.toString()
    (tz for offset, tz of @table when _offset == offset)[0]

  # Return the guessed timezone for this browser
  @timezone: -&amp;gt;
    x = new Date
    @lookup_by_offset(-x.getTimezoneOffset())

$(document).ready =&amp;gt;

  # Find timezone selected marked for autofill
  tz_select = $(".time_zone select")
  $("select.timezone.autofill").val(Timezone.timezone())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the selector is conditional on an &lt;strong&gt;autofill&lt;/strong&gt; class being
present. We don&amp;rsquo;t want to just reset all timezone selects if
they have been manually set by the user.&lt;/p&gt;

&lt;p&gt;In our formtastic code we can now write&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;= semantic_form_for @widget do |f|
  = f.inputs do
    - autofill = @widget.timezone ? nil : 'autofill'
    = f.input :timezone, :as =&amp;gt; :time_zone, 
                         :input_html =&amp;gt; disabled_hash, 
                         :input_html =&amp;gt; { :class =&amp;gt; "timezone #{autofill}" }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now when we create a new form that requires a timezone to be entered then
the select will default to the timezone of the browser. This may not be
the correct one and the user has the option of changing the option.&lt;/p&gt;

&lt;p&gt;Happy timezones.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>RSpec meta expectations over collections</title>
    <link rel="alternate" href="http://xtargets.com/2011/08/12/rspec-meta-expectations-over-collections/"/>
    <id>http://xtargets.com/2011/08/12/rspec-meta-expectations-over-collections/</id>
    <published>2011-08-12</published>
    <updated>2011-08-12</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;Found myself writing specs like&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;describe "1..10" do

    before :each do
        @array = [1,2,3,4,5,6,7,8,9]
    end

    it "should have every item as numeric" do
&lt;/code&gt;&lt;/pre&gt;
</summary>
    <content type="html">&lt;p&gt;Found myself writing specs like&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;describe "1..10" do

    before :each do
        @array = [1,2,3,4,5,6,7,8,9]
    end

    it "should have every item as numeric" do
        @array.each {|i|
            i.should be_kind_of(Numeric)
        }
    end


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

&lt;p&gt;And I didn&amp;rsquo;t like it. I wanted&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;describe "1..10" do

    before :each do
        @array = [1,2,3,4,5,6,7,8,9]
    end

    it "should have every item as numeric" do
        @array.should each be_kind_of(Numeric)
    end

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

&lt;p&gt;and here is the solution and it is very simple.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;RSpec::Matchers.define :each do |meta|
  match do |actual|
    actual.each_with_index do |i, j|
      @elem = j
      i.should meta
    end
  end

  failure_message_for_should do |actual|
    "at[#{@elem}] #{meta.failure_message_for_should}"
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and some specs to demonstrate&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;describe "passing" do
  it "should be a number" do
    (1..10).should each be_kind_of(Numeric)
  end
end

describe "failing" do
  it "should not be a string" do
    [1,2,3,4,"cow",6,"7"].should each be_kind_of(Numeric)
  end
end

describe "failing again" do
  subject{[1,2,3,4,"cow",6,"7"]}
  it{should each be_kind_of(Numeric)}
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;enjoy&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Stubbing Time.zone.now in Rails for fun and profit</title>
    <link rel="alternate" href="http://xtargets.com/2011/08/11/stubbing-timezonenow-in-rails-for-fun-and-profit/"/>
    <id>http://xtargets.com/2011/08/11/stubbing-timezonenow-in-rails-for-fun-and-profit/</id>
    <published>2011-08-11</published>
    <updated>2011-08-11</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;Having lots of queries in my project that depend on Time.now and
having Time.now scattered around my code was starting to cause me
testing/bdding/specing headaches. RSpec stubbing to the rescue! With&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;Having lots of queries in my project that depend on Time.now and
having Time.now scattered around my code was starting to cause me
testing/bdding/specing headaches. RSpec stubbing to the rescue! With
the below helper you can code like Marty Mcfly.&lt;/p&gt;

&lt;p&gt;Throw this file in spec/support/time_helper.rb&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require 'rspec/mocks'

class Time
  DEFAULT_STOP_ZONE = ActiveSupport::TimeZone["UTC"]
  def Time.stop
    RSpec::Mocks::setup(self)
    @stopped_time = DEFAULT_STOP_ZONE.now
    Time.zone = DEFAULT_STOP_ZONE
    Time.zone.stub!(:now).and_return {
      @stopped_time
    }
    Time.stub!(:now).and_return {@stopped_time}
  end

  def Time.advance duration
    raise "You have not stopped time yet McFly!" unless @stopped_time
    @stopped_time = @stopped_time.since duration
  end

  def Time.regress duration
    raise "You have not stopped time yet McFly!" unless @stopped_time
    @stopped_time = @stopped_time.since -duration
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then in your spec can write things like below&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;describe Foo do
    before :each do

        Time.stop

        (1..10).each do |i|
            Factory :foo, :created_at =&amp;gt; Time.now.ago(i.hours)
        end

        (1..10).each do |i|
            Factory :foo, :created_at =&amp;gt; Time.now.since(i.hours)
        end

    end

    it "should have 10 elements created in the future" do
        Foo.where{created_at &amp;gt; my{Time.now}}.count.should == 10
    end

    it "should have 10 elements created in the past" do
        Foo.where{created_at &amp;lt; my{Time.now}}.count.should == 10
    end

    describe "advancing time" do
        before :each do
            Time.advance 1.5.hours
        end

        it "should have 9 elements created in the future" do
            Foo.where{created_at &amp;gt; my{Time.now}}.count.should == 10
        end

        it "should have 11 elements created in the past" do
            Foo.where{created_at &amp;lt; my{Time.now}}.count.should == 10
        end

    end

    describe "regressing time" do
        before :each do
            Time.regress 1.5.hours
        end

        it "should have 11 elements created in the future" do
            Foo.where{created_at &amp;gt; my{Time.now}}.count.should == 10
        end

        it "should have 9 elements created in the past" do
            Foo.where{created_at &amp;lt; my{Time.now}}.count.should == 10
        end

    end

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

&lt;p&gt;The solution is good as long as you don&amp;rsquo;t care about absolute time. Sometimes
you will need to set the current absoute time. You can do this through the
stopped_time accessor monkey patched into Time.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Tableless views with active record</title>
    <link rel="alternate" href="http://xtargets.com/2011/08/02/tableless-views-with-active-record/"/>
    <id>http://xtargets.com/2011/08/02/tableless-views-with-active-record/</id>
    <published>2011-08-02</published>
    <updated>2011-08-02</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;ActiveRecord is great. It is awsome. The new ActiveRelation support for chaining
and query building is amazing. However ActiveRecord is table bound. This means
you cannot create models that do not exist as tables. Why would you want to do
this?&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;ActiveRecord is great. It is awsome. The new ActiveRelation support for chaining
and query building is amazing. However ActiveRecord is table bound. This means
you cannot create models that do not exist as tables. Why would you want to do
this?&lt;/p&gt;

&lt;p&gt;For example say we have two simple models&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class GameAward &amp;lt; ActiveRecord::Base

    attr_accessible :points, :date

    has_many :tags


class Tag &amp;lt; ActiveRecord::Base

    attr_accessible :name

    belongs_to :game_award
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and we have an associated table called game_awards. We would like to create
a query that returns the number of points each tag is associated with. This
would be an SQL statement something like&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;select sum(points) as points, tag.name as name from game_awards 
join tags on 
    tags.game_awards_id = game_awards.id
group by
    tags.name
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&amp;rsquo;s all very well if we were into writing SQL by hand but we are
much too hip for that. And wqe have another problem. What model should
the above query be associated with. Is it a Tag model or is it
a GameAward model. I say it is neither. It is the result of joining
and transforming the data from two other tables.&lt;/p&gt;

&lt;p&gt;We need a third model. Let&amp;rsquo;s call that Stats&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Stat &amp;lt; ActiveRecord::Base
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;At this point ActiveRecord will puke because there is no table called
Stats. We need to trick ActiveRecord into letting us play in the sandbox
without bringing our own bucket and spades. We will create a wrapper
called VirtualRecord that provides the shims we need. First of all
how might we use such a VirtualRecord in our Stats class&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Stat &amp;lt; VirtualRecord
    column :points, :integer
    column :name,   :string

    def self.find_all
        select{
            [sum(game_awards.points).as points, tags.name as name]
        }.from{game_awards}.join{tags}.group{tags.name}
    end

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

&lt;p&gt;We would need to define some query to return all the records from the database.
I have done the above with SQUEEL&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;https://github.com/ernie/squeel
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;an excellent query builder DSL. Check it out! The find_all method is hooked
by the VirtualRecord class to provide a default_scope that when you call&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Stat.all
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;you generate the above query. It is ActiveRelation friendly and can be chained.
The implementation of the VirtualRecord is&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# requires the squeel gem
#
# https://github.com/ernie/squeel
# 
# Inherit from this class to create tableless
# models that are backed by a query.
#
# For example
#
# class Award &amp;lt; ActiveRecord::Base
#   has_many :award_type_view
# end
#
# class AwardTypeView &amp;lt; VirtualRecord
#   column :award_type, :string
#   column :award_id, :integer
#
#   belongs_to :award
#
#   def self.find_all
#     select{[awards.type.as(award_type), awards.id.as(award_id)]}.from("awards")
#   end
# end
#
# The cool thing is, is that the relations work on both directions
#
# a = AwardTypeView.first
#
#   SELECT "award_type_views".* FROM 
#   (SELECT "awards"."type" AS award_type, "awards"."id" AS award_id FROM awards ) 
#   award_type_views LIMIT 1
#
# a.award
#
#   SELECT "awards".* FROM "awards" WHERE "awards"."id" = 1 LIMIT 1
#
# b = Award.first
#
#   SELECT "awards".* FROM "awards" LIMIT 1
#
# b.award_type_views
#
#   SELECT "award_type_views".* FROM 
#   (SELECT "awards"."type" AS award_type, "awards"."id" AS award_id FROM awards ) 
#   award_type_views 
#   WHERE "award_type_views"."award_id" = 1
class VirtualRecord &amp;lt; ActiveRecord::Base
  def self.columns() 
    @columns ||= [] 
  end  

  def self.columns_hash()
    @columns_hash ||= {}
  end

  def self.find_all
    raise "please override"
  end

  def self.inherited klass 
    default_scope do
      table = klass.to_s.underscore.pluralize
      q = klass.find_all.arel.as table
      select{}.from(q)
    end
  end

  def self.column(name, sql_type = :string, default = nil, null = true)  
    column = ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)  

    columns &amp;lt;&amp;lt; column
    columns_hash[name.to_s] = column   
  end  

  self.abstract_class = true

  def self.table_name
    to_s.underscore.pluralize
  end

  def readonly?
    true
  end

end
&lt;/code&gt;&lt;/pre&gt;
</content>
  </entry>
  <entry>
    <title>Binding model attributes to form elements with backbone js</title>
    <link rel="alternate" href="http://xtargets.com/2011/06/11/binding-model-attributes-to-form-elements-with-backbone-js/"/>
    <id>http://xtargets.com/2011/06/11/binding-model-attributes-to-form-elements-with-backbone-js/</id>
    <published>2011-06-11</published>
    <updated>2011-06-11</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;If you are familiar with &lt;a href="http://documentcloud.github.com/backbone/#View"&gt;backbone js&lt;/a&gt; then you know the
events declaration for views.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class FooView extends Backbone.View

  tag: "div"

  events:

    "click .button" : "doButton"

  doButton: -&amp;gt;

    alert("Button Clicked. I rock!")

  render: -&amp;gt;

    $(@el).html """
      &amp;lt;div class="button"&amp;gt; click me &amp;lt;/div&amp;gt;
    """

    super

    @
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;However when tying the model&amp;rsquo;s attributes to view elements we can use
a similar trick.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class FooView extends MyView

  tag: "div"

  modelBindings:

    "change form input.address" : "address"
    "change form input.name"    : "name"
    "change form input.email"   : "email"

  render: -&amp;gt;

    $(@el).html """
      &amp;lt;form&amp;gt;
        &amp;lt;input class="address"/&amp;gt;
        &amp;lt;input class="name"/&amp;gt;
        &amp;lt;input class="email"/&amp;gt;
      &amp;lt;/form&amp;gt;
    """

    super

    @


# Instantiate the view 
view = new FooView
  model: new Backbone.Model

$("body").html(view.el)
&lt;/code&gt;&lt;/pre&gt;
</summary>
    <content type="html">&lt;p&gt;If you are familiar with &lt;a href="http://documentcloud.github.com/backbone/#View"&gt;backbone js&lt;/a&gt; then you know the
events declaration for views.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class FooView extends Backbone.View

  tag: "div"

  events:

    "click .button" : "doButton"

  doButton: -&amp;gt;

    alert("Button Clicked. I rock!")

  render: -&amp;gt;

    $(@el).html """
      &amp;lt;div class="button"&amp;gt; click me &amp;lt;/div&amp;gt;
    """

    super

    @
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;However when tying the model&amp;rsquo;s attributes to view elements we can use
a similar trick.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class FooView extends MyView

  tag: "div"

  modelBindings:

    "change form input.address" : "address"
    "change form input.name"    : "name"
    "change form input.email"   : "email"

  render: -&amp;gt;

    $(@el).html """
      &amp;lt;form&amp;gt;
        &amp;lt;input class="address"/&amp;gt;
        &amp;lt;input class="name"/&amp;gt;
        &amp;lt;input class="email"/&amp;gt;
      &amp;lt;/form&amp;gt;
    """

    super

    @


# Instantiate the view 
view = new FooView
  model: new Backbone.Model

$("body").html(view.el) 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;No messy manual handling of events. Totally declarative binding. We only need
to extend the render method and  add the following code to our View base class.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class MyView extends Backbone.View

  render: -&amp;gt;

    if @model != null
      # Iterate through all bindings
      for selector, field of @modelBindings
        do (selector, field) =&amp;gt;
          console.log "binding #{selector} to #{field}"
          # When the model changes update the form
          # elements
          @model.bind "change:#{field}", (model, val)=&amp;gt;
            console.log "model[#{field}] =&amp;gt; #{selector}"
            @$(selector).val(val)

          # When the form changes update the model
          [event, selector...] = selector.split(" ")
          selector = selector.join(" ")
          @$(selector).bind event, (ev)=&amp;gt;
            console.log "form[#{selector}] =&amp;gt; #{field}"
            data = {}
            data[field] = @$(ev.target).val()
            @model.set data

          # Set the initial value of the form
          # elements
          @$(selector).val(@model.get(field))

    super

    @
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now you have declarative form element binding for backbone. It might
not handle all complex use cases but for the basic stuff it cut&amp;rsquo;s
down the boiler plate quite a bit.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Rails 3.1 Asset pipeline rocks!</title>
    <link rel="alternate" href="http://xtargets.com/2011/05/29/rails-31-asset-pipeline-rocks/"/>
    <id>http://xtargets.com/2011/05/29/rails-31-asset-pipeline-rocks/</id>
    <published>2011-05-29</published>
    <updated>2011-05-29</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;app/assets/javascripts/m/crazy.js.coffee.erb&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class &amp;lt;%= "CRAZY" %&amp;gt;
  &amp;lt;%(1..10).each do |p|%&amp;gt;
  method_&amp;lt;%=p%&amp;gt;: -&amp;gt;
    &amp;lt;%=p%&amp;gt;
  &amp;lt;%end%&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;automagically ends up as&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(function() {
  var CRAZY;
  CRAZY = (function() {
    function CRAZY() {}
    CRAZY.prototype.method_1 = function() {
      return 1;
    };
    CRAZY.prototype.method_2 = function() {
      return 2;
    };
    CRAZY.prototype.method_3 = function() {
      return 3;
    };
    CRAZY.prototype.method_4 = function() {
      return 4;
    };
    CRAZY.prototype.method_5 = function() {
      return 5;
    };
    CRAZY.prototype.method_6 = function() {
      return 6;
    };
    CRAZY.prototype.method_7 = function() {
      return 7;
    };
    CRAZY.prototype.method_8 = function() {
      return 8;
    };
    CRAZY.prototype.method_9 = function() {
      return 9;
    };
    CRAZY.prototype.method_10 = function() {
      return 10;
    };
    return CRAZY;
  })();
}).call(this);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the cascade of mime types  crazy.js.coffee.erb. I&amp;rsquo;m going to use
this to introspect my ActiveRecord classes and generate backbone.js
classes with all boiler plate stuff filled in&amp;hellip;&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;app/assets/javascripts/m/crazy.js.coffee.erb&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class &amp;lt;%= "CRAZY" %&amp;gt;
  &amp;lt;%(1..10).each do |p|%&amp;gt;
  method_&amp;lt;%=p%&amp;gt;: -&amp;gt;
    &amp;lt;%=p%&amp;gt;
  &amp;lt;%end%&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;automagically ends up as&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(function() {
  var CRAZY;
  CRAZY = (function() {
    function CRAZY() {}
    CRAZY.prototype.method_1 = function() {
      return 1;
    };
    CRAZY.prototype.method_2 = function() {
      return 2;
    };
    CRAZY.prototype.method_3 = function() {
      return 3;
    };
    CRAZY.prototype.method_4 = function() {
      return 4;
    };
    CRAZY.prototype.method_5 = function() {
      return 5;
    };
    CRAZY.prototype.method_6 = function() {
      return 6;
    };
    CRAZY.prototype.method_7 = function() {
      return 7;
    };
    CRAZY.prototype.method_8 = function() {
      return 8;
    };
    CRAZY.prototype.method_9 = function() {
      return 9;
    };
    CRAZY.prototype.method_10 = function() {
      return 10;
    };
    return CRAZY;
  })();
}).call(this);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the cascade of mime types  crazy.js.coffee.erb. I&amp;rsquo;m going to use
this to introspect my ActiveRecord classes and generate backbone.js
classes with all boiler plate stuff filled in.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Automagically create a style guide with SASS that will make you and your designer happy</title>
    <link rel="alternate" href="http://xtargets.com/2011/05/19/automagically-create-a-style-guide-with-sass-that-will-make-you-and-your-designer-happy/"/>
    <id>http://xtargets.com/2011/05/19/automagically-create-a-style-guide-with-sass-that-will-make-you-and-your-designer-happy/</id>
    <published>2011-05-19</published>
    <updated>2011-05-19</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;Communication with a designer in your project is not always easy. They work with Adobe
Illustrator. You work with HTML and SASS. It would be nice to have a middle ground where
you can quickly confirm styles and layouts without resorting to full application examples.
We have created a style guide which we automatically generate by parsing some simple SASS
files that we enforce naming conventions on&amp;hellip;&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;Communication with a designer in your project is not always easy. They work with Adobe
Illustrator. You work with HTML and SASS. It would be nice to have a middle ground where
you can quickly confirm styles and layouts without resorting to full application examples.
We have created a style guide which we automatically generate by parsing some simple SASS
files that we enforce naming conventions on.&lt;/p&gt;

&lt;p&gt;The page we generate is something like below&lt;/p&gt;

&lt;p&gt;&lt;img src="https://img.skitch.com/20110519-mu3wc8fey9m3775n1j66a512un.jpg" alt="Style Guide" /&gt;&lt;/p&gt;

&lt;p&gt;Part of the haml template that generates the above is below&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  %dl
  - XTargets::Sass.swatches.each do |c|
    %dt .#{c}
    %dd{:class=&amp;gt;"#{c} character-transparent"}
      xxx
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The above uses a simple parser to extract the style names from the below SASS file&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;//////////////////////////////////////////////////////////////////////////////////
// Color Variables
//////////////////////////////////////////////////////////////////////////////////

//////// Framework Colors - DO NOT CHANGE
$color-transparent     : rgba(0  , 0   , 0    , 0)
$color-white           : rgb(255 , 255, 255)
$color-black           : rgb(0   , 0   , 0)

//////// Designer Defined Colors
$color-light-blue      : rgb(230 , 230 , 255)
$color-egg             : rgb(203 , 219 , 231)
$color-dark-grey       : rgb(227 , 228 , 208)
$color-light-grey      : rgb(85  , 85  , 85 )
$color-maroon          : rgb(153 , 153 , 153)
$color-royal-blue      : rgb(157 , 11  , 14 )
$color-text-callout    : rgb(0   , 110 , 165)
$color-pale-olive      : rgb(204 , 204 , 204)

//////////////////////////////////////////////////////////////////////////////////
// Flat Background Colors
//////////////////////////////////////////////////////////////////////////////////
.color-background-black
  background-color: $color-black

.color-background-white
  background-color: $color-white

.color-background-light-blue
  background-color: $color-light-blue

.color-background-egg
  background-color: $color-egg

.color-background-dark-grey
  background-color: $color-dark-grey

.color-background-light-grey
  background-color: $color-light-grey

.color-background-maroon
  background-color: $color-maroon

.color-background-royal-blue
  background-color: $color-royal-blue

.color-background-text-callout
  background-color: $color-text-callout

.color-background-pale-olive
  background-color: $color-pale-olive
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I enforce a naming convention so it&amp;rsquo;s easy to extract the style names
and generate a style guide page. The parser is a very simple regexp
filter&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;module XTargets
  class Sass
    SASS_DIR = File.expand_path "../../../app/stylesheets/partials/", __FILE__
    SWATCH_FILE = File.join SASS_DIR, "_swatches.sass"

    # Yields
    def self.swatches
      style SWATCH_FILE, 'color-background'
    end

    def self.style file_name, prefix_pattern
      File.open(file_name).each_line.select do |line|
        line =~ /^\.#{prefix_pattern}/
      end.collect do |line|
          line[1..-1].chomp
      end
    end

  end
end
&lt;/code&gt;&lt;/pre&gt;
</content>
  </entry>
  <entry>
    <title>Who needs Cucumber?</title>
    <link rel="alternate" href="http://xtargets.com/2011/05/12/who-needs-cucumber/"/>
    <id>http://xtargets.com/2011/05/12/who-needs-cucumber/</id>
    <published>2011-05-12</published>
    <updated>2011-05-12</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;I&amp;rsquo;ve played with cucumber and honestly it doesn&amp;rsquo;t work for me. It&amp;rsquo;s the
complete opposite of DRY. It&amp;rsquo;s RYO ( repeat yourself often ). The thinking
behind it is to get readable specs for your clients. However with a bit
of refactoring you can make capybara rspec based integration tests
look beautiful.&lt;/p&gt;

&lt;p&gt;Here is a simple integration spec I wrote to test some tags functionality&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;I&amp;rsquo;ve played with cucumber and honestly it doesn&amp;rsquo;t work for me. It&amp;rsquo;s the
complete opposite of DRY. It&amp;rsquo;s RYO ( repeat yourself often ). The thinking
behind it is to get readable specs for your clients. However with a bit
of refactoring you can make capybara rspec based integration tests
look beautiful.&lt;/p&gt;

&lt;p&gt;Here is a simple integration spec I wrote to test some tags functionality&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require 'spec_helper'

describe "Tags" do

  before do
    @post1 = Factory.create :post, :tag_list =&amp;gt; 'tag_a,tag_b,tag_c'
    @post2 = Factory.create :post, :tag_list =&amp;gt; 'tag_a,tag_b'
    @post3 = Factory.create :post, :tag_list =&amp;gt; 'tag_a'
  end

  include PostPageHelpers

  it "should show all articles when no tags are clicked" do

    visit posts_path

    within post_tags_section @post1 do
      page.should have_content "tag_a"
      page.should have_content "tag_b"
      page.should have_content "tag_c"
    end

    within post_tags_section @post2 do
      page.should have_content "tag_a"
      page.should have_content "tag_b"
      page.should_not have_content "tag_c"
    end

    within post_tags_section @post3 do
      page.should have_content "tag_a"
      page.should_not have_content "tag_b"
      page.should_not have_content "tag_c"
    end

  end


  it "should filter based on tags" do

    visit posts_path

    within post_tags_section(@post1) do
      click_on "tag_a"
    end

    page.should have_post @post1 
    page.should have_post @post2 
    page.should have_post @post3 

    within post_tags_section(@post1) do
      click_on "tag_b"
    end

    page.should have_post @post1 
    page.should have_post @post2 
    page.should_not have_post @post3 

    within post_tags_section(@post1) do
      click_on "tag_c"
    end

    page.should have_post @post1 
    page.should_not have_post @post2 
    page.should_not have_post @post3 
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The trick is to factor out the messy css selector
garbage into helper methods with meaningful names.
The implementation of the helper is below&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;module PostPageHelpers
  def have_post(post)
    have_css "section.post_#{post.id}"
  end

  def post_tags_section(post)
    "section.post_#{post.id} .tags"
  end
end
&lt;/code&gt;&lt;/pre&gt;
</content>
  </entry>
  <entry>
    <title>Using Webmock to bridge http calls to Rack::Test</title>
    <link rel="alternate" href="http://xtargets.com/2011/05/09/using-webmock-to-bridge-http-calls-to-racktest/"/>
    <id>http://xtargets.com/2011/05/09/using-webmock-to-bridge-http-calls-to-racktest/</id>
    <published>2011-05-09</published>
    <updated>2011-05-09</updated>
    <author>
      <name>Brad Phelan</name>
    </author>
    <summary type="html">&lt;p&gt;&lt;a href="https://github.com/bblimke/webmock"&gt;Webmock&lt;/a&gt; is a neat library for
stubbing out http requests in your application so as not to have
to make real ones during your testing. Normally in one of your models
or controllers you would be making a request to some external webservice
say google.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;stub_request(:get, "http://google.com").to_return("some string")
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and then anywhere you make an http request to http://google.com in your
application you get returned &amp;ldquo;some string&amp;rdquo;. Neat. However we can abuse
this to do something more interesting with Rack::Test. Rack::Test provides&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;post
put
delete
head
get
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;methods to interact with your system without having to spin up a real
server and the overhead that entail. However if you have a complex
protocol to test for which a ruby client library exists,&lt;br/&gt;
it would be nice to bridge the client library into Rack::Test so
that you can use it directly instead of having to reinvent
the wheel and call :get, :post, etc directly&amp;hellip;&lt;/p&gt;
</summary>
    <content type="html">&lt;p&gt;&lt;a href="https://github.com/bblimke/webmock"&gt;Webmock&lt;/a&gt; is a neat library for
stubbing out http requests in your application so as not to have
to make real ones during your testing. Normally in one of your models
or controllers you would be making a request to some external webservice
say google.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;stub_request(:get, "http://google.com").to_return("some string")
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and then anywhere you make an http request to http://google.com in your
application you get returned &amp;ldquo;some string&amp;rdquo;. Neat. However we can abuse
this to do something more interesting with Rack::Test. Rack::Test provides&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;post
put
delete
head
get
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;methods to interact with your system without having to spin up a real
server and the overhead that entail. However if you have a complex
protocol to test for which a ruby client library exists,&lt;br/&gt;
it would be nice to bridge the client library into Rack::Test so
that you can use it directly instead of having to reinvent
the wheel and call :get, :post, etc directly.&lt;/p&gt;

&lt;p&gt;Using Webmock this turns out to be very easy and
is shown in the code below.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;module HttpToRack
    # @param method [Symbol] the http method to bridge to Rack::Test.
    # @param uri [String] the end point to intercept
    def http_to_rack(method, uri)

      stub_request(method, uri).to_return( lambda { |request|

        case request.method
        when :post
          post request.uri.path, request.body, request.headers
        when :put
          post request.uri.path, request.body, request.headers
        when :get
          get request.uri.path, request.headers
        when :delete
          delete request.uri.path, request.headers
        when :head
          head request.uri.path, request.headers
        else
          raise "#{request.method} not supported"
        end

        { :body =&amp;gt; response.body, 
          :headers =&amp;gt; response.headers 
        }

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

&lt;p&gt; If you are testing your pingback route for an integration test and there is
some class PingBackDriver that does some fancy XMLRPC for example that the
pingback route responds to then you can use PingBackDriver directly but use
http_to_rack to bridge those specific calls to Rack::Test&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; it "should follow the pingback protocol http://www.hixie.ch/specs/pingback/pingback-1.0 " do

   # The post that is the target of the pingback
   http_to_rack :any, "http://www.example.com/posts/1"

   # The pingback server
   http_to_rack :any, "http://www.example.com/pingback"

   PingBackDriver.ping \
            :source_uri =&amp;gt; "http://www.example.com/posts/2", 
            :target_uri =&amp;gt; "http://www.example.com/posts/1" 

 end
&lt;/code&gt;&lt;/pre&gt;
</content>
  </entry>
</feed>

