<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:refactormycode.com,2007:users856friends</id>
  <link type="application/atom+xml" href="http://refactormycode.com/users/856/friends" rel="self"/>
  <title>Tien Dung 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" href="http://refactormycode.com/codes/491-very-simple-rack-framework" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/373-password-update-code" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code291</id>
    <published>2008-05-06T10:39:27+00:00</published>
    <updated>2008-05-08T09:00:31+00:00</updated>
    <title>[C#] Pointers in C#</title>
    <content type="html">&lt;p&gt;I am trying to work out how unmanged objects work in C# but for some reason it looks like my objects arn't properly initized. Could someone help me out here? &lt;/p&gt;

&lt;pre&gt;using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace Pointers {
    unsafe class Program {
        static unsafe void Main( string[ ] args ) {
            Unsafe unsafeObject = new Unsafe( 1, 2, 3, 4 );

            Console.WriteLine(
                &amp;quot;FirstLocation[ &amp;quot; + unsafeObject.firstLocation-&amp;gt;ToString( ) + &amp;quot; ]\n&amp;quot; +
                &amp;quot;SecondLocation[ &amp;quot; + unsafeObject.secondLocation-&amp;gt;ToString( ) + &amp;quot; ]&amp;quot;
            );

            Console.Read( );
        }
    }

    unsafe struct Unsafe {
        public Safe* firstLocation, secondLocation;

        public Unsafe( int fl_x, int fl_y, int sl_x, int sl_y ) {
            Safe ffl = new Safe( fl_x, fl_y ),
                 fsl = new Safe( sl_x, sl_y );

            this.firstLocation = &amp;amp;ffl;
            this.secondLocation = &amp;amp;fsl;
        }
    }

    struct Safe {
        public int x, y;

        public Safe( int x, int y ){
            this.x = x;
            this.y = y;
        }

        public override string ToString( ) {
            return this.x + &amp;quot;,&amp;quot; + this.y;
        }
    }
}

## Expected output
FirstLocation[ 1,2 ]
SecondLocation[ 3,4 ]

## Given output
FirstLocation[ 14,67169456 ]
SecondLocation[ 19593296,19593248 ]
&lt;/pre&gt;</content>
    <author>
      <name>Andre Steenveld</name>
      <email></email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/291-pointers-in-c" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/271-ruby-has_finder-on-has_many" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code192</id>
    <published>2007-12-20T21:54:34+00:00</published>
    <updated>2007-12-22T03:14:03+00:00</updated>
    <title>[Ruby] Challenge: Ugliest Ruby FizzBuzz</title>
    <content type="html">&lt;p&gt;So, after seeing some ugly fizzbuzzes, instead of trying to create the best fizzbuzz ever (an easy task), we decided the worst fizzbuzz ever would be a bigger challenge.&lt;/p&gt;

&lt;p&gt;Oh, and before you ask, it's because spaceships are awesome.&lt;/p&gt;

&lt;pre&gt;class Fixnum
  def &amp;lt;=&amp;gt;(b)
    self % b
  end
  
  def fizz?
    self % 3 == 0
  end
  
  def buzz?
    self % 5 == 0
  end
end

(1..100).each do |number|
  if number.fizz?
    if number.buzz?
      puts 'FizzBuzz'
    else
      puts 'Fizz'
    end
  else
    puts 'Buzz'
  end
end&lt;/pre&gt;</content>
    <author>
      <name>jamesgolick</name>
      <email>jamesgolick@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/192-challenge-ugliest-ruby-fizzbuzz" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/152-handling-nil-object" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code137</id>
    <published>2007-11-05T20:27:18+00:00</published>
    <updated>2007-11-06T01:02:42+00:00</updated>
    <title>[Ruby] resource_controller: Redesign My API</title>
    <content type="html">&lt;p&gt;Backstory on my blog: &lt;a href="http://jamesgolick.com/2007/11/5/resource_controller-redesign-my-api-at-refactormycode-com" target="_blank"&gt;http://jamesgolick.com/2007/11/5/resource_controller-redesign-my-api-at-refactormycode-com&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;## Before / After / Response

class PostsController &amp;lt; ResourceController::Base

  # block syntax
  create do
    before { @post.user = current_user }
    response do |wants|
      wants.html
      wants.js
    end
  end
  
  # chain syntax
  update.failure.wants.js
  
  # hybrid syntax
  update.failure do
    flash &amp;quot;There was a problem saving your object.&amp;quot;
    wants.js
  end

end

## Alternate Model/Route/Object Naming

class PostsController &amp;lt; ResourceController::Base
  private
    def model_name
      'blog_post'
    end
    
    def route_name
      'article'
    end
end

## Alternate find syntax

class PostsController &amp;lt; ResourceController::Base
  private
    def object
      @object ||= end_of_association_chain.find_by_permalink(param)
    end
    
    def collection
      @collection ||= end_of_association_chain.find(:all, :page =&amp;gt; {:current =&amp;gt; params[:page], :size =&amp;gt; 10})
    end
end

## Specific Actions

class PostsController &amp;lt; ResourceController::Base
  actions :all, :except =&amp;gt; :edit
end

## Possible Parents

class PostsController &amp;lt; ResourceController::Base
  belongs_to :user, :category
end&lt;/pre&gt;</content>
    <author>
      <name>jamesgolick</name>
      <email>jamesgolick@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/137-resource_controller-redesign-my-api" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/112-rails-migration-conflict-repair" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/78-dynamic-migrations-for-rails" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/63-open-a-new-tab-in-current-directory-from-iterm" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/29-rating-system-for-this-site" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor48</id>
    <published>2007-09-27T10:41:28+00:00</published>
    <title>[Ruby] On restful_authentication role requirements</title>
    <content type="html">&lt;p&gt;So, I added this&lt;/p&gt;

&lt;pre&gt;## application.rb

def self.requires_role(role)
  before_filter :login_required
  send(:define_method, :authorized?) do
    logged_in? &amp;amp;&amp;amp; current_user.send(&amp;quot;#{role}?&amp;quot;)
  end
end

## controller

requires_role :administrator&lt;/pre&gt;</content>
    <author>
      <name>jamesgolick</name>
      <email>jamesgolick@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/20-restful_authentication-role-requirements/refactors/48" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code20</id>
    <published>2007-09-27T10:40:32+00:00</published>
    <updated>2007-09-27T10:40:32+00:00</updated>
    <title>[Ruby] restful_authentication role requirements</title>
    <content type="html">&lt;p&gt;This is a couple of lines that I was writing a lot&lt;/p&gt;

&lt;pre&gt;## Controller that can only be accessed by an administrator

before_filter :login_required

# ... the controller

private
  def authorized?
    logged_in? &amp;amp;&amp;amp; current_user.administrator?
  end&lt;/pre&gt;</content>
    <author>
      <name>jamesgolick</name>
      <email>jamesgolick@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/20-restful_authentication-role-requirements" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/17-arrow-code/refactors/43" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/16-extracting-style-from-a-css-file" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/14-is-this-year-a-leap-year/refactors/39" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/15-feature-sections-in-code" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/9-sum-string-sizes/refactors/37" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/14-is-this-year-a-leap-year/refactors/34" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/13-link_to_remote_with_spinner/refactors/32" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/11-test-file-to-code-file-ratio/refactors/31" rel="alternate"/>
  </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" href="http://refactormycode.com/codes/14-is-this-year-a-leap-year/refactors/30" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor29</id>
    <published>2007-09-21T07:22:05+00:00</published>
    <title>[Ruby] On Test file to code file ratio</title>
    <content type="html">&lt;p&gt;Well, here is a more ruby way of doing that - although I'm usually quite fond of the backticks myself :)&lt;/p&gt;

&lt;pre&gt;Dir.glob(&amp;quot;test/**/*_test.rb&amp;quot;).size.to_f / Dir.glob(&amp;quot;app/**/*.rb&amp;quot;).size.to_f &lt;/pre&gt;</content>
    <author>
      <name>danielharan</name>
      <email>chebuctonian@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/11-test-file-to-code-file-ratio/refactors/29" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Code13</id>
    <published>2007-09-20T14:17:41+00:00</published>
    <updated>2007-09-24T20:36:21+00:00</updated>
    <title>[Ruby] link_to_remote_with_spinner</title>
    <content type="html">&lt;p&gt;We use this utility internally. I had a use case today where I don't want to $('#{container_id}').hide(); rather I'd like to grey it out and stop it from receiving events. Is there a more generic way to do all this?&lt;/p&gt;

&lt;pre&gt;# Behave like +link_to_remote+, but shows a spinner while the request is processing.
#   link_to_remote_with_spinner 'Hi', :url =&amp;gt; hi_path
# You can specify the spinner and the container to hide
#   link_to_remote_with_spinner 'Hi', :url =&amp;gt; hi_path, :container_id =&amp;gt; 'container', :spinner =&amp;gt; 'spinner'
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;)
    
    out &amp;lt;&amp;lt; link_to_remote(title, { :loading =&amp;gt; &amp;quot;$('#{container_id}').hide(); $('#{spinner}').show()&amp;quot; }.merge(options),
                                 { :id =&amp;gt; element_id })
  end
end&lt;/pre&gt;</content>
    <author>
      <name>danielharan</name>
      <email>chebuctonian@gmail.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/13-link_to_remote_with_spinner" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor25</id>
    <published>2007-09-20T12:12:51+00:00</published>
    <title>[Ruby] On Knowing mocha</title>
    <content type="html">&lt;p&gt;Awesome! Mocha has such a nice API, I don't understand ppl that like Flexmock!&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>macournoyer</name>
      <email>macournoyer@yahoo.ca</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/12-knowing-mocha/refactors/25" rel="alternate"/>
  </entry>
</feed>
