<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:refactormycode.com,2007:users2friends</id>
  <link type="application/atom+xml" rel="self" href="http://refactormycode.com/users/2/friends"/>
  <title>jamesgolick friends</title>
  <updated>Sun Sep 14 18:11:09 +0000 2008</updated>
  <entry>
    <id>tag:refactormycode.com,2007:Code491</id>
    <published>2008-09-14T18:11:09+00:00</published>
    <updated>2008-09-14T18:48:08+00:00</updated>
    <title>[Ruby] Very Simple Rack framework</title>
    <content type="html">&lt;p&gt;I'll be presenting &lt;a href="http://rack.rubyforge.org" target="_blank"&gt;http://rack.rubyforge.org&lt;/a&gt; this Tuesday at the first Montreal Against Rails (&lt;a href="http://www.montrealonrails.com/2008/09/11/montreal_against_rails-tuesday" target="_blank"&gt;http://www.montrealonrails.com/2008/09/11/montreal_against_rails-tuesday&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;I'll show how to use Rack and then I'd like to try something new (and probably crazy-stupid). Building a web framework with Rack is so easy, I'll be doing pair programming with anyone from the audience to create our own custom framework live during the presentation (in 30 min). We'll start with the code posted here on RefactorMyCode as the application code, we'll implement the framework code during the presentation. So submit your ideas here before the event.&lt;/p&gt;

&lt;p&gt;And make sure to RSVP (&lt;a href="http://upcoming.yahoo.com/event/1093407" target="_blank"&gt;http://upcoming.yahoo.com/event/1093407&lt;/a&gt;) if your in Montreal next Tuesday!&lt;/p&gt;

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

&lt;pre&gt;# This is what an application build with our framework would look like.
# Run with:
#   rackup app.ru

app = App.new do
  
  get &amp;quot;&amp;quot; do
    render &amp;quot;hi&amp;quot; # Specifies the body of the response
  end
  
  get &amp;quot;echo/(.*)&amp;quot; do |text| # Regexp matches are passed as block args
    render text
  end
  
  get &amp;quot;session/set&amp;quot; do
    session[params.first.key] = params.first.value
  end
  get &amp;quot;session&amp;quot; do
    render session.inspect
  end
  
  get &amp;quot;form&amp;quot; do
    render erb(:form) # Can have helper methods to render erb and the like
  end
  
  post &amp;quot;form&amp;quot; do
    render params.inspect
  end
  
end

run app&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/491-very-simple-rack-framework"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code373</id>
    <published>2008-07-16T16:59:17+00:00</published>
    <updated>2008-07-18T02:46:37+00:00</updated>
    <title>[Ruby] Password update code</title>
    <content type="html">&lt;p&gt;Mostly straight from a tutorial, but it's uuuugly:&lt;/p&gt;

&lt;pre&gt;class AccountsController &amp;lt; ApplicationController

  layout 'application'
  before_filter :login_required, :except =&amp;gt; :show

  # Change password action  
  def update
  return unless request.put?
    # we authenticate with email 
    if Dj.authenticate(current_dj.email, params[:old_password])
      if ((params[:password] == params[:password_confirmation]) &amp;amp;&amp;amp; !params[:password_confirmation].blank?)
        current_dj.password_confirmation = params[:password_confirmation]
        current_dj.password = params[:password]        
    if current_dj.save
        flash[:notice] = &amp;quot;Password successfully updated.&amp;quot;
        redirect_to dj_path(current_dj.login) #profile_url(current_dj.login)
      else
        flash[:error] = &amp;quot;An error occured, your password was not changed.&amp;quot;
        render :action =&amp;gt; 'edit'
      end
    else
      flash[:error] = &amp;quot;New password does not match the password confirmation.&amp;quot;
      @old_password = params[:old_password]
      render :action =&amp;gt; 'edit'      
     end
   else
      flash[:error] = &amp;quot;Your old password is incorrect.&amp;quot;
      render :action =&amp;gt; 'edit'
    end 
  end    
end
&lt;/pre&gt;</content>
    <author>
      <name>danielharan</name>
      <email>chebuctonian@gmail.com</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/373-password-update-code"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code271</id>
    <published>2008-04-01T16:10:13+00:00</published>
    <updated>2008-04-09T22:58:51+00:00</updated>
    <title>[Ruby] Ruby has_finder on has_many ?</title>
    <content type="html">&lt;p&gt;This smells... one of the main points of using has_finder was to isolate domain logic to the appropriate model (&lt;a href="http://jamesgolick.com/2008/2/25/plugins-i-ve-known-and-loved-2-has_finder" target="_blank"&gt;http://jamesgolick.com/2008/2/25/plugins-i-ve-known-and-loved-2-has_finder&lt;/a&gt;), but here it's scattered again.&lt;/p&gt;

&lt;p&gt;Any ideas on how to elegantly clean this up?&lt;/p&gt;

&lt;pre&gt;class JobBoard &amp;lt; ActiveRecord::Base
  has_many :job_board_postings
  
  has_finder :distributed_by, lambda {|distributor_code| {:conditions =&amp;gt; ['distributor = ?', distributor_code.to_s]} }
  has_finder :push,   :conditions =&amp;gt; {:push =&amp;gt; true}
  has_finder :manual, :conditions =&amp;gt; {:manual =&amp;gt; true}
  
  def push
    ! pull
  end
  alias_method :push?, :push
end

class JobBoardPosting &amp;lt; ActiveRecord::Base
  belongs_to :job
  belongs_to :job_board

  has_finder :distributed_by, lambda {|distributor_code| {:conditions =&amp;gt; ['job_boards.distributor = ?', distributor_code.to_s], :include =&amp;gt; :job_board} }
  
  # TODO: couldn't this be a delegated finder? not very DRY
  has_finder :pushed, :conditions =&amp;gt; [&amp;quot;job_boards.pull = ?&amp;quot;, false],  :include =&amp;gt; :job_board
  has_finder :manual, :conditions =&amp;gt; [&amp;quot;job_boards.manual = ?&amp;quot;, true], :include =&amp;gt; :job_board
end&lt;/pre&gt;</content>
    <author>
      <name>danielharan</name>
      <email>chebuctonian@gmail.com</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/271-ruby-has_finder-on-has_many"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code240</id>
    <published>2008-02-20T04:38:08+00:00</published>
    <updated>2010-03-15T16:00:05+00:00</updated>
    <title>[Ruby] DataMapper threaded benchmark</title>
    <content type="html">&lt;p&gt;third of three - slowest of those tested, even though it's thread-safe - why?&lt;/p&gt;

&lt;pre&gt;require 'rubygems'
require 'data_mapper'
require 'benchmark'

DataMapper::Database.setup({ :adapter =&amp;gt; 'sqlite3', :database =&amp;gt; 'perf_dm.db' })

# set up DataMapper
class DmItem
  include DataMapper::Persistence
  set_table_name 'items'
  property :name, :string
  property :description, :text
  property :active, :boolean
  property :created_at, :datetime
end
database.save(DmItem)
# DataMapper::Persistence.auto_migrate!

1000.times do |i|
  x = DmItem.new(:name =&amp;gt; &amp;quot;record_#{i}&amp;quot;, :description =&amp;gt; &amp;quot;test record&amp;quot;, :active =&amp;gt; i.remainder(3).zero?)
  x.save
end

# run benchmarks
Benchmark.bmbm do |x|
  
  x.report('DataMapper single-thread') do
    100.times do
      DmItem.all(:active =&amp;gt; false)
    end
  end
  
  x.report('DataMapper threaded') do
    threads = []
    10.times do
      t = Thread.new do
        10.times do
          DmItem.all(:active =&amp;gt; false)
        end
      end
      threads.push(t)
    end
    threads.each { |t| t.join }
  end
  
end

&lt;/pre&gt;</content>
    <author>
      <name>Kevin Williams</name>
      <email>kevwil@gmail.com</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/240-datamapper-threaded-benchmark"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code239</id>
    <published>2008-02-20T04:35:56+00:00</published>
    <updated>2009-08-30T01:18:31+00:00</updated>
    <title>[Ruby] Sequel threaded benchmark</title>
    <content type="html">&lt;p&gt;second of three, not as fast as ActiveRecord - why?&lt;/p&gt;

&lt;pre&gt;require 'rubygems'
require 'sequel'
require 'benchmark'

# set up Sequel
Sequel::Model.db = DB = Sequel.sqlite('perf_sequel.db')

class SequelItem &amp;lt; Sequel::Model(:items)
  set_schema do
    primary_key :id
    varchar :name
    text :description
    boolean :active
    timestamp :created_at
  end
end

# create schema and populate
SequelItem.create_table!

1000.times do |i|
  DB[:items].insert(:name =&amp;gt; &amp;quot;record_#{i}&amp;quot;, :description =&amp;gt; &amp;quot;test record&amp;quot;, :active =&amp;gt; i.remainder(3).zero?, :created_at =&amp;gt; Time.now)
end

# run benchmarks
Benchmark.bmbm do |x|
  
  x.report('sequel single-thread') do
    100.times do
      SequelItem.where(:active =&amp;gt; false).all
    end
  end
  
  x.report('sequel threaded') do
    threads = []
    10.times do
      t = Thread.new do
        10.times do
          SequelItem.where(:active =&amp;gt; false).all
        end
      end
      threads.push(t)
    end
    threads.each { |t| t.join }
  end
  
end

SequelItem.drop_table

&lt;/pre&gt;</content>
    <author>
      <name>Kevin Williams</name>
      <email>kevwil@gmail.com</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/239-sequel-threaded-benchmark"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code238</id>
    <published>2008-02-20T04:33:28+00:00</published>
    <updated>2010-02-16T11:16:10+00:00</updated>
    <title>[Ruby] ActiveRecord threaded benchmark</title>
    <content type="html">&lt;p&gt;first of three benchmarks, expected AR to be slowest but it was fastest - why?&lt;/p&gt;

&lt;pre&gt;require 'rubygems'
require 'active_record'
require 'benchmark'

ActiveRecord::Base.establish_connection :adapter =&amp;gt; 'sqlite3', :database =&amp;gt; 'perf_ar.db'

# set up ActiveRecord
class ArItem &amp;lt; ActiveRecord::Base
  set_table_name 'items'
end

# created schema and data
class NewItem &amp;lt; ActiveRecord::Migration
  def self.up
    create_table :items do |t|
      t.column :name, :string
      t.column :description, :text
      t.column :active, :boolean
      t.column :created_at, :datetime
    end
  end
  def self.down
    drop_table :items
  end
end
NewItem.up

1000.times do |i|
  ArItem.create(:name =&amp;gt; &amp;quot;record_#{i}&amp;quot;, :description =&amp;gt; &amp;quot;test record&amp;quot;, :active =&amp;gt; i.remainder(3).zero?)
end

# run benchmarks
Benchmark.bmbm do |x|
  
  x.report('active_record single-thread') do
    100.times do
      ArItem.find(:all, :conditions =&amp;gt; [&amp;quot;active = ?&amp;quot;, false])
    end
  end
  
  x.report('active_record threaded') do
    ActiveRecord::Base.allow_concurrency = true
    threads = []
    10.times do
      t = Thread.new do
        10.times do
          ArItem.find(:all, :conditions =&amp;gt; [&amp;quot;active = ?&amp;quot;, false])
        end
      end
      threads.push(t)
    end
    threads.each { |t| t.join }
  end
  
end
ActiveRecord::Base.verify_active_connections!
NewItem.down

&lt;/pre&gt;</content>
    <author>
      <name>Kevin Williams</name>
      <email>kevwil@gmail.com</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/238-activerecord-threaded-benchmark"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code152</id>
    <published>2007-11-14T02:07:08+00:00</published>
    <updated>2007-12-27T04:00:00+00:00</updated>
    <title>[Ruby] Handling nil object</title>
    <content type="html">&lt;p&gt;@post.category can be nil, or not.
&lt;br /&gt;Any cleaner way of doing this?&lt;/p&gt;

&lt;pre&gt;## [html_rails]
&amp;lt;%= (@post.category ? @post.category.name : '') + ' ' + link_to(@post.title, post_path(@post)) %&amp;gt;&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/152-handling-nil-object"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code112</id>
    <published>2007-10-26T18:25:22+00:00</published>
    <updated>2007-10-29T20:57:29+00:00</updated>
    <title>[Ruby] Rails migration conflict repair</title>
    <content type="html">&lt;p&gt;Explained here: &lt;a href="http://www.danielharan.com/2007/10/26/rails-migrations-handling-naming-conflicts/" target="_blank"&gt;http://www.danielharan.com/2007/10/26/rails-migrations-handling-naming-conflicts/&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;namespace :migrations do
  
  desc 'reverts, renames and re-executes uncommitted migrations that conflict with already committed migrations'
  task :repair =&amp;gt; :environment do
    uncommitted = `svn status`.select {|line| line =~ /db\/migrate\//}.collect {|line| line.match(/ db\/migrate\/(.*rb)/)[1]}
    committed   = Dir.glob('db/migrate/*').collect {|line| line.match(/db\/migrate\/(.*rb)/)[1]} - uncommitted
    
    highest_committed   = committed.collect(&amp;amp;:to_i).max
    lowest_uncommitted  = uncommitted.collect(&amp;amp;:to_i).min
    
    schema_version = ActiveRecord::Base.connection.select_one(&amp;quot;select version from schema_info&amp;quot;)[&amp;quot;version&amp;quot;].to_i
    
    # revert uncommitted migrations
    uncommitted.sort_by(&amp;amp;:to_i).reverse.each do |migration|
      version = migration.to_i
      if version &amp;lt;= schema_version
        name = migration.match(/(\d*_.*).rb/)[1]
        class_name = (require 'db/migrate/' + name)[0]
        puts class_name.constantize.down 
      end
    end
    
    #set it back to the version prior to all the uncommitted migrations - this doesn't get done automatically by calling down
    ActiveRecord::Base.connection.execute(&amp;quot;update schema_info set version=#{schema_version-1}&amp;quot;)
    
    version_offset = (highest_committed - lowest_uncommitted) + 1
    
    uncommitted.each do |old_name|
      version  = old_name.to_i + version_offset
      new_name = version.to_s.rjust(3,'0') + old_name.gsub(/\d/, '')
      `mv db/migrate/#{old_name} db/migrate/#{new_name}`
    end
    
    puts &amp;quot;Uncommited migrations have been reversed and renamed. You can now migrate.&amp;quot;
  end
end&lt;/pre&gt;</content>
    <author>
      <name>danielharan</name>
      <email>chebuctonian@gmail.com</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/112-rails-migration-conflict-repair"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code78</id>
    <published>2007-10-12T04:27:08+00:00</published>
    <updated>2007-10-12T04:30:57+00:00</updated>
    <title>[Ruby] Dynamic migrations for rails</title>
    <content type="html">&lt;p&gt;How do you create a rails project if you don't know the schema in advance? ERB to the rescue!&lt;/p&gt;

&lt;p&gt;Blogged background: &lt;a href="http://www.danielharan.com/2007/10/12/rails-migration-hackery-with-erb/" target="_blank"&gt;http://www.danielharan.com/2007/10/12/rails-migration-hackery-with-erb/&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;require 'erb'
class ClientMigrator
  def self.create(fields)
    erb_migration = ERB.new &amp;lt;&amp;lt;-EOS
  class AddClients &amp;lt; ActiveRecord::Migration
    def self.up
      create_table :clients do |t|
        &amp;lt;% fields.each do |name, type| %&amp;gt;t.column :&amp;lt;%= name %&amp;gt;, :&amp;lt;%= type %&amp;gt;
        &amp;lt;% end %&amp;gt;
      end
    end

    def self.down
      drop_table :clients
    end
  end
EOS
    File.open(&amp;quot;db/migrate/003_add_clients.rb&amp;quot;, &amp;quot;w+&amp;quot;) do |f|
      f.puts erb_migration.result(binding)
    end
    `rake db:migrate`
  end
end

# Example call
ClientMigrator.create(:name =&amp;gt; :string, :phone =&amp;gt; :string)&lt;/pre&gt;</content>
    <author>
      <name>danielharan</name>
      <email>chebuctonian@gmail.com</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/78-dynamic-migrations-for-rails"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code63</id>
    <published>2007-10-04T18:07:03+00:00</published>
    <updated>2007-10-04T18:07:03+00:00</updated>
    <title>[Bash] Open a new tab in current directory from iTerm</title>
    <content type="html">&lt;p&gt;Here's a small script I wrote to open a new tab in iTerm in the current directory. I place this in my .bash_profile and use it a lot to start Rails server and open a new tab to work in: tab; script/server
&lt;br /&gt;Know any better way of doing this ?&lt;/p&gt;

&lt;p&gt;Btw, I'm also introducing a new language in here: Bash :) Hope you like it!&lt;/p&gt;

&lt;p&gt;Also, I know the server is bloody slow, sorry for that. I'm migrating to a new and absurdly fast server at the moment. Hang on!&lt;/p&gt;

&lt;pre&gt;tab() # new tab from current dir
{
osascript -e &amp;quot;
tell application \&amp;quot;iTerm\&amp;quot;
 tell the first terminal
  launch session \&amp;quot;Default Session\&amp;quot;
  tell the last session
   write text \&amp;quot;cd $(pwd)\&amp;quot;
  end tell
 end tell
end tell&amp;quot;
}&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/63-open-a-new-tab-in-current-directory-from-iterm"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code29</id>
    <published>2007-09-29T14:09:19+00:00</published>
    <updated>2007-09-29T19:27:17+00:00</updated>
    <title>[JavaScript] Rating system for this site</title>
    <content type="html">&lt;p&gt;Here's the code of the rating system I built for this site.
&lt;br /&gt;Have any suggestions on how to improve it ?&lt;/p&gt;

&lt;p&gt;Thanks
&lt;/p&gt;

&lt;pre&gt;var Rating = Class.create();
Rating.prototype = {
  initialize: function(element, rating, options) {
    this.element = $(element);
    this.rating  = rating;
    this.maxRating = 5;
    this.options = options || {};
    
    this.bindedOnHover = this.onHover.bindAsEventListener(this);
    this.bindedOnExit  = this.onExit.bindAsEventListener(this);
    this.bindedOnClick  = this.onClick.bindAsEventListener(this);
    
    Event.observe(this.element, 'mouseover', this.bindedOnHover);
    Event.observe(this.element, 'mouseout', this.bindedOnExit);
    Event.observe(this.element, 'click', this.bindedOnClick);
    
    this.instanciateStars();
    this.showStarts(this.rating);
  },
  
  instanciateStars: function() {
    this.maxRating.times(function() {
      var img = document.createElement('img');
      this.element.appendChild(img);
    }.bind(this));
  },
  
  showStarts: function(number) {
    var stars = this.getStars();

    $R(0, number-1).each (function(position) {
      stars[position].src = '/images/star_full.png';
    });
    $R(number, this.maxRating-1).each (function(position) {
      stars[position].src = '/images/star_empty.png';
    });
  },
  
  getStars: function() {
    return this.element.getElementsBySelector('img');
  },
  
  onHover: function(event) {
    var element = Event.element(event);
    if (element.tagName == 'IMG') {
      this.showStarts(this.findRatingFromEvent(element));
    }
  },
  
  onExit: function(event) {
    this.showStarts(this.rating);
  },
  
  onClick: function(event) {
    var element = Event.element(event);
    if (element.tagName == 'IMG' &amp;amp;&amp;amp; this.options.onClick) {
      this.options.onClick.bind(this)(this.findRatingFromEvent(element));
    }
  },
  
  findRatingFromEvent: function(element) {
    var r = 0;
    this.getStars().each(function(star) {
      r ++;
      if (star == element) {
        throw $break;
      }
    });
    return r;
  },
  
  disable: function() {
    Event.stopObserving(this.element, 'mouseover', this.bindedOnHover);
    Event.stopObserving(this.element, 'mouseout', this.bindedOnExit);
    Event.stopObserving(this.element, 'click', this.bindedOnClick);
  }
};

## Usage [html]
&amp;lt;div class=&amp;quot;rating&amp;quot;&amp;gt;
  &amp;lt;span id=&amp;quot;rating_97&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;img alt=&amp;quot;Spinner&amp;quot; class=&amp;quot;spinner&amp;quot; id=&amp;quot;rating_97_spinner&amp;quot; src=&amp;quot;spinner.gif&amp;quot; style=&amp;quot;display:none&amp;quot; /&amp;gt;
  &amp;lt;span id=&amp;quot;rating_97_count&amp;quot; class=&amp;quot;count&amp;quot;&amp;gt;
    No rating. You haven't rated it!
  &amp;lt;/span&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;
  var rating_97 = new Rating('rating_97', 0, {
    onClick: function(rating) {
      $('rating_97_spinner').show();
      $('rating_97_count').hide();
      this.disable();
      new Ajax.Request('/codes/16-extracting-style-from-a-css-file/refactors/97;rate', {
        parameters: 'rating=' + rating,
        onComplete: function() {
          $('rating_97_spinner').hide();
          $('rating_97_count').show();
        }
      });
    }
  });
&amp;lt;/script&amp;gt;&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/29-rating-system-for-this-site"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor58</id>
    <published>2007-09-27T17:52:29+00:00</published>
    <title>[Ruby] On Integer puzzle</title>
    <content type="html">&lt;p&gt;wrong! see my proof&lt;/p&gt;

&lt;pre&gt;puts chars[51000000000] == 's' # =&amp;gt; false&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/8-integer-puzzle/refactors/58"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor56</id>
    <published>2007-09-27T15:51:45+00:00</published>
    <title>[Ruby] On Ruby simple loop</title>
    <content type="html">&lt;p&gt;Right! Forgot about that one (upto). Definatly easier to read, nice one meebo!&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/2-ruby-simple-loop/refactors/56"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor54</id>
    <published>2007-09-27T12:30:13+00:00</published>
    <title>[Ruby] On restful_authentication role requirements</title>
    <content type="html">&lt;p&gt;I don't think you need the send on define_method if you're doing this in the class. It's a class method.&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/20-restful_authentication-role-requirements/refactors/54"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor50</id>
    <published>2007-09-27T11:43:23+00:00</published>
    <title>[Ruby] On restful_authentication role requirements</title>
    <content type="html">&lt;p&gt;What about this:&lt;/p&gt;

&lt;pre&gt;def self.requires_role(role, options={})
  before_filter(options) { logged_in? &amp;amp;&amp;amp; current_user.send(&amp;quot;#{role}?&amp;quot;) ? true : access_denied }
end

## In your controller
require_role :admin, :only =&amp;gt; [:destroy]
require_role :author, :except =&amp;gt; [:index, :show]&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/20-restful_authentication-role-requirements/refactors/50"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor49</id>
    <published>2007-09-27T10:45:27+00:00</published>
    <title>[Ruby] On restful_authentication role requirements</title>
    <content type="html">&lt;p&gt;Really good idea James, but what if some actions require admin, other to be the author and stuff like that ?&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/20-restful_authentication-role-requirements/refactors/49"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor43</id>
    <published>2007-09-26T17:18:50+00:00</published>
    <title>[Ruby] On Arrow Code</title>
    <content type="html">&lt;p&gt;Why not restructure everything in a more OO way ? Everything seems to be around analysing a line so why not make a Line class with specialized subclasses.&lt;/p&gt;

&lt;pre&gt;class Line
  def parse
    skip_line
  end
end

class Parsable &amp;lt; Line
  def parse
    @line_stack.pop
  end
end

class Nested &amp;lt; Parsable
  def parse
    # do parsing
  end
end

class Attribute &amp;lt; Nested
  def parse
    parse_attribute
  end
end
&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/17-arrow-code/refactors/43"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code16</id>
    <published>2007-09-25T21:18:29+00:00</published>
    <updated>2007-09-26T15:01:59+00:00</updated>
    <title>[Ruby] Extracting style from a CSS file</title>
    <content type="html">&lt;p&gt;Here's a Rake task I use to extract style attributes from a CSS file to later embed it in some HTML (for the pastable version of the code)&lt;/p&gt;

&lt;p&gt;I can't seem to match a regex over more then 1 line even with the multiline option. So in trucated the lines before matching them.&lt;/p&gt;

&lt;p&gt;There must be a better way of doing this! Any idea ?&lt;/p&gt;

&lt;pre&gt;task :extract_style do
  css = File.read 'public/stylesheets/code.css'
  css.gsub! &amp;quot;{\n&amp;quot;, '{'
  css.gsub! &amp;quot;;\n&amp;quot;, ';'
  
  output = ''
  
  output &amp;lt;&amp;lt; &amp;quot;module Style\n&amp;quot;
  output &amp;lt;&amp;lt; &amp;quot;  EMBEDED = {\n&amp;quot;
  output &amp;lt;&amp;lt; css.grep(/\.code pre \.(\w+) \{(.*)\}/) do
    &amp;quot;    #{(':' + $1).ljust(25)} =&amp;gt; '#{$2.delete(' ')}'&amp;quot;
  end.join(&amp;quot;,\n&amp;quot;)
  output &amp;lt;&amp;lt; &amp;quot;\n  }\n&amp;quot;
  output &amp;lt;&amp;lt; &amp;quot;end&amp;quot;
  
  File.open(&amp;quot;app/models/style.rb&amp;quot;, 'w') { |f| f &amp;lt;&amp;lt; output }
end&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/16-extracting-style-from-a-css-file"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor39</id>
    <published>2007-09-23T13:13:03+00:00</published>
    <title>[JavaScript] On Is this year a leap year?</title>
    <content type="html">&lt;p&gt;Nice tip Gary! I didn't know about this idom!&lt;/p&gt;

&lt;p&gt;And about sections, how about that:&lt;/p&gt;

&lt;pre&gt;## Ruby code [ruby]
def code
  puts 'cool'
end

## View (rhtml) [html_rails]
&amp;lt;h1&amp;gt;&amp;lt;%= @title %&amp;gt;&amp;lt;/h1&amp;gt;

## Javascript [javascript]
var Page = {
  omg: function() {
    alert('img');
  }
};
&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/14-is-this-year-a-leap-year/refactors/39"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code15</id>
    <published>2007-09-22T08:44:57+00:00</published>
    <updated>2007-09-22T22:08:13+00:00</updated>
    <title>[Ruby] [FEATURE] Sections in code!</title>
    <content type="html">&lt;p&gt;Introducing a new feature: sections in code!
&lt;br /&gt;Simply add: &amp;quot;## My section name&amp;quot; on top of a section in your code and it will be splited w/ a cute title! More info at &lt;a href="http://refactormycode.com/help/code" target="_blank"&gt;http://refactormycode.com/help/code&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here's the code that does this with my test cases. I'm sure y'all can do better!&lt;/p&gt;

&lt;p&gt;Thanks to Gary for suggesting that feature!&lt;/p&gt;

&lt;p&gt;*Note* I replaced ## with -## (dash) in the test cases or it would have been interpreted as section. I still need to figure out how to escape those! Got an idea on how to do this ?&lt;/p&gt;

&lt;p&gt;I know the highlithing is broken! damn those &amp;lt;&amp;lt;-EOS&lt;/p&gt;

&lt;pre&gt;class CodeFormatter
  cattr_reader :syntaxes
  @@syntaxes = Uv.syntaxes.sort
  
  def initialize(code, language)
    @code = code
    @language = language
  end
  
  def syntax
    @language.downcase
  end
  
  def valid_syntax?(syntax)
    self.class.syntaxes.include? syntax
  end
  
  def split_in_sections
    current_section = Section.new(syntax)
    sections = [current_section]
  
    @code.split(&amp;quot;\n&amp;quot;).each do |line|
      if matches = line.chomp.match(/^\s*##\s?(.+?)(?:\s+\[(.+)\])?$/)
        current_section = Section.new(valid_syntax?(matches[2]) ? matches[2] : syntax, matches[1])
        sections &amp;lt;&amp;lt; current_section
      else
        current_section &amp;lt;&amp;lt; line
      end
    end
  
    # Remove the first anonymous section if empty
    sections.delete_at(0) if sections[0].code.empty? &amp;amp;&amp;amp; sections.size &amp;gt; 1
  
    sections
  end

  class Section
    attr_accessor :code, :title, :syntax
  
    def initialize(syntax, title=nil)
      @syntax = syntax
      @title = title
      @code = ''
    end
  
    def &amp;lt;&amp;lt;(code)
      @code &amp;lt;&amp;lt; code &amp;lt;&amp;lt; &amp;quot;\n&amp;quot;
    end
  end
end

## Tests
def test_split_in_sections
  formatter = CodeFormatter.new(&amp;lt;&amp;lt;-EOS, 'Ruby')
    -## My code
    def code
      1
    end
  
    -## Test
    def test_code
      assert_equal 1, code
    end
  EOS
  
  assert_equal 2, formatter.split_in_sections.size
  assert_equal 'My code', formatter.split_in_sections[0].title
  assert_match /^\s+def code/m, formatter.split_in_sections[0].code
  assert_equal 'Test', formatter.split_in_sections[1].title
  assert_match /^\s+def test_code/m, formatter.split_in_sections[1].code
end

def test_split_in_sections_with_no_sections
  formatter = CodeFormatter.new(&amp;lt;&amp;lt;-EOS, 'Ruby')
    def test_code
      assert_equal 1, code
    end    
  EOS
  
  assert_equal 1, formatter.split_in_sections.size
  assert_equal nil, formatter.split_in_sections[0].title
  assert_match /^\s+def test_code/m, formatter.split_in_sections[0].code
end

def test_split_in_sections_with_first_section_anonymous
  formatter = CodeFormatter.new(&amp;lt;&amp;lt;-EOS, 'Ruby')
    def code
      1
    end
  
    -## Test
    def test_code
      assert_equal 1, code
    end    
  EOS

  assert_equal 2, formatter.split_in_sections.size
  assert_equal nil, formatter.split_in_sections[0].title
  assert_match /^\s+def code/m, formatter.split_in_sections[0].code
  assert_equal 'Test', formatter.split_in_sections[1].title
  assert_match /^\s+def test_code/m, formatter.split_in_sections[1].code
end

def test_syntax_in_section
  formatter = CodeFormatter.new(&amp;lt;&amp;lt;-EOS, 'Ruby')
    def code
      1
    end
    
    -## View [html_rails]
    &amp;lt;h1&amp;gt;&amp;lt;%= @title %&amp;gt;&amp;lt;/h1&amp;gt;
    
    -## Invalid syntax [invalid]
    &amp;lt;h1&amp;gt;&amp;lt;%= @title %&amp;gt;&amp;lt;/h1&amp;gt;
  EOS

  assert_equal 'ruby', formatter.split_in_sections[0].syntax
  assert_equal 'View', formatter.split_in_sections[1].title
  assert_equal 'html_rails', formatter.split_in_sections[1].syntax
  assert_equal 'ruby', formatter.split_in_sections[2].syntax
end
&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/15-feature-sections-in-code"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor37</id>
    <published>2007-09-21T10:13:43+00:00</published>
    <title>[Ruby] On Sum string sizes</title>
    <content type="html">&lt;p&gt;Welcome to the site Hampton! Nice defactoring!&lt;/p&gt;

&lt;p&gt;But... counting in memory ?? This is so old school! Using file is much much faster, better, stronger!!&lt;/p&gt;

&lt;pre&gt;units = %w{ one two three four five six seven eight nine }

File.open('counter.txt', 'w') do |f|
  units.each do |unit|
    f &amp;lt;&amp;lt; unit
  end
end

puts File.size('counter.txt')&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/9-sum-string-sizes/refactors/37"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor34</id>
    <published>2007-09-21T08:20:51+00:00</published>
    <title>[JavaScript] On Is this year a leap year?</title>
    <content type="html">&lt;p&gt;I'll try to add sections with ## like pastie, thx for the feedback Gary.
&lt;br /&gt;But that sure is a lot of !!(!negation != !false)&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/14-is-this-year-a-leap-year/refactors/34"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor32</id>
    <published>2007-09-21T07:42:00+00:00</published>
    <title>[Ruby] On link_to_remote_with_spinner</title>
    <content type="html">&lt;p&gt;With the above code you could already specify the onComplete callback overriding the container hiding thing, I just added the same thing for the loading callback and now you got more freedom then a jobless freelancer on crack.&lt;/p&gt;

&lt;pre&gt;def link_to_remote_with_spinner(title, options)
  element_id = options.delete(:id) || ('link_to_' + title.underscore.tr(' ', '_'))
  container_id = options.delete(:container_id) || element_id
  
  returning '' do |out|
    unless spinner = options.delete(:spinner)
      spinner = &amp;quot;#{element_id}_spinner&amp;quot;
      out &amp;lt;&amp;lt; image_tag('spinner.gif', :id =&amp;gt; spinner, :style =&amp;gt; 'display:none')
    end
    options[:complete] = &amp;quot;$('#{spinner}').hide(); &amp;quot; + (options[:complete] || &amp;quot;$('#{container_id}').show()&amp;quot;)
    options[:loading] = &amp;quot;$('#{spinner}').show(); &amp;quot; + (options[:loading] || &amp;quot;$('#{container_id}').hide()&amp;quot;)
    
    out &amp;lt;&amp;lt; link_to_remote(title, options, { :id =&amp;gt; element_id })
  end
end

# Now if you specify complete and loading you can do wathever you want:
link_to_remote_with_spinner 'Grey out text', :url =&amp;gt; ouch_path, :id =&amp;gt; 'my_link',
                            :loading =&amp;gt; toggle = &amp;quot;$('my_link').toggleClassName('disabled')&amp;quot;,
                            :complete =&amp;gt; toggle
                            
link_to_remote_with_spinner 'Dont click!', :url =&amp;gt; ouch_path,
                            :loading =&amp;gt; &amp;quot;$('notice').update('I told you not to click')&amp;quot;,
                            :complete =&amp;gt; &amp;quot;$('notice').update('Ok now! Look what you did, stupid!')&amp;quot;
&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/13-link_to_remote_with_spinner/refactors/32"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor31</id>
    <published>2007-09-21T07:34:27+00:00</published>
    <title>[Ruby] On Test file to code file ratio</title>
    <content type="html">&lt;p&gt;Nice! Or even shorter, with the [] alias&lt;/p&gt;

&lt;pre&gt;Dir[&amp;quot;test/**/*_test.rb&amp;quot;].size.to_f / Dir[&amp;quot;app/**/*.rb&amp;quot;].size.to_f &lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/11-test-file-to-code-file-ratio/refactors/31"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor30</id>
    <published>2007-09-21T07:30:04+00:00</published>
    <title>[JavaScript] On Is this year a leap year?</title>
    <content type="html">&lt;p&gt;I'm pretty sure the last year % 100 == 0 is not needed as we already test w/ a multiple of 100 (400), plus we now can remove parenthesis.&lt;/p&gt;

&lt;pre&gt;Object.extend(Date.prototype, {
  isLeap: function(){
    var year = this.getFullYear();
    return year % 4 == 0 &amp;amp;&amp;amp; year % 100 != 0 || year % 400 == 0;
  }
});&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" rel="alternate" href="http://refactormycode.com/codes/14-is-this-year-a-leap-year/refactors/30"/>
  </entry>
</feed>
