<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users210</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/210" rel="self"/>
  <title>Jason Dew</title>
  <updated>Mon Feb 02 19:06:57 -0800 2009</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code735</id>
    <published>2009-02-02T19:06:57-08:00</published>
    <updated>2009-02-02T19:09:40-08:00</updated>
    <title>[Haskell] Pseudo Genetic Programming</title>
    <content type="html">&lt;p&gt;This code probably needs cleanup and definitely could use a performance boost.  I wanted to parallelize some parts of it but didn't have any luck...&lt;/p&gt;

&lt;p&gt;It takes an image and generates an image of random rectangles with the same dimensions.  Then it mutates that image to see if the mutation is a closer match to the target image than the original random image.  Rinse and repeat.&lt;/p&gt;

&lt;p&gt;Blog post with some references: &lt;a href="http://jasondew.com/2009/02/02/pseudo-genetic-programming-in-haskell" target="_blank"&gt;http://jasondew.com/2009/02/02/pseudo-genetic-programming-in-haskell&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;import Prelude hiding (lookup)
import System.Random
import Control.Monad
import Graphics.GD
import Foreign.C.Types
import Data.Bits
import Data.Map hiding (map)
import Data.Time
import Text.Printf
 
type Rectangle = (Point, Point, Color)
type DNA = [Rectangle]
 
numberOfObjects :: Int
numberOfObjects = 5
 
numberOfAdditions :: Int
numberOfAdditions = 1
 
additionProbability :: Int
additionProbability = 1
 
mutationProbability :: Int
mutationProbability = 10
 
numberOfIterations :: Int
numberOfIterations = 1000000
 
snapshotEvery :: Int
snapshotEvery = 10
 
jpegQuality :: Int
jpegQuality = 90
 
targetPath :: String
targetPath = &amp;quot;monalisa.jpg&amp;quot;
 
-- =======================================================================================================================
 
targetImage :: IO Image
targetImage = loadJpegFile targetPath
 
targetPixelColors :: Int -&amp;gt; Int -&amp;gt; IO [(Point, Color)]
targetPixelColors width height = do image &amp;lt;- targetImage
                                    mapM (\point -&amp;gt; mapColor image point) [(x, y) | x &amp;lt;- [1..width], y &amp;lt;- [1..height]]
                                 where mapColor image point = do color &amp;lt;- getPixel point image
                                                                 return (point, color)
 
randomNumberGenerator = randomR (0, 100)
randomRGBGenerator = randomR (0, 255)
randomAlphaGenerator = randomR (0, 127)
 
randomColor :: IO Color
randomColor = do red &amp;lt;- getStdRandom randomRGBGenerator
                 green &amp;lt;- getStdRandom randomRGBGenerator
                 blue &amp;lt;- getStdRandom randomRGBGenerator
                 alpha &amp;lt;- getStdRandom randomAlphaGenerator
                 return $ rgba red green blue alpha
 
alpha :: Num a =&amp;gt; Color -&amp;gt; a
alpha color = fromIntegral $ color `shiftR` 24
 
red :: Num a =&amp;gt; Color -&amp;gt; a
red color = fromIntegral $ (color .&amp;amp;. 16711680) `shiftR` 16
 
green :: Num a =&amp;gt; Color -&amp;gt; a
green color = fromIntegral $ (color .&amp;amp;. 65280) `shiftR` 8
 
blue :: Num a =&amp;gt; Color -&amp;gt; a
blue color = fromIntegral $ color .&amp;amp;. 255
 
randomPoint :: Int -&amp;gt; Int -&amp;gt; IO Point
randomPoint maxX maxY = do x &amp;lt;- getStdRandom $ randomR (0, maxX)
                           y &amp;lt;- getStdRandom $ randomR (0, maxY)
                           return (x, y)
 
randomRectangle :: Int -&amp;gt; Int -&amp;gt; IO Rectangle
randomRectangle maxX maxY = do start &amp;lt;- randomPoint maxX maxY
                               end &amp;lt;- randomPoint maxX maxY
                               color &amp;lt;- randomColor
                               return (start, end, color)
 
drawRectangle :: Rectangle -&amp;gt; Image -&amp;gt; IO ()
drawRectangle (start, end, color) image = drawFilledRectangle start end color image
 
initialDNA :: Int -&amp;gt; Int -&amp;gt; Int -&amp;gt; IO DNA
initialDNA objects maxX maxY = sequence [randomRectangle maxX maxY | _ &amp;lt;- [1..objects]]
 
drawDNAImage :: Int -&amp;gt; Int -&amp;gt; IO DNA -&amp;gt; IO Image
drawDNAImage width height ioDNA = do image &amp;lt;- newImage (width, height)
                                     dna &amp;lt;- ioDNA
                                     mapM_ (\rectangle -&amp;gt; drawRectangle rectangle image) dna
                                     return image
 
mutatedValue :: Int -&amp;gt; Int -&amp;gt; IO Int
mutatedValue original max = do offset &amp;lt;- getStdRandom $ randomR (0, max)
                               return $ (original + offset) `mod` max
 
maybeMutateValue :: Int -&amp;gt; Int -&amp;gt; IO Int
maybeMutateValue original max = do randomNumber &amp;lt;- getStdRandom randomNumberGenerator
                                   case randomNumber &amp;lt; mutationProbability of
                                     True -&amp;gt; mutatedValue original max
                                     False -&amp;gt; return original
 
maybeMutatePoint :: Point -&amp;gt; Int -&amp;gt; Int -&amp;gt; IO Point
maybeMutatePoint (x, y) maxX maxY = do newX &amp;lt;- maybeMutateValue x maxX
                                       newY &amp;lt;- maybeMutateValue y maxY
                                       return (newX, newY)
 
maybeMutateColor :: Color -&amp;gt; IO Color
maybeMutateColor original = do possiblyMutatedRed &amp;lt;- maybeMutateValue (red original) 255
                               possiblyMutatedGreen &amp;lt;- maybeMutateValue (green original) 255
                               possiblyMutatedBlue &amp;lt;- maybeMutateValue (blue original) 255
                               possiblyMutatedAlpha &amp;lt;- maybeMutateValue (alpha original) 127
                               return $ rgba possiblyMutatedRed possiblyMutatedGreen possiblyMutatedBlue possiblyMutatedAlpha
 
maybeMutateRectangle :: Rectangle -&amp;gt; Int -&amp;gt; Int -&amp;gt; IO Rectangle
maybeMutateRectangle rectangle maxX maxY = do randomNumber &amp;lt;- getStdRandom randomNumberGenerator
                                              case randomNumber &amp;lt; mutationProbability of
                                                True -&amp;gt; mutateRectangle rectangle maxX maxY
                                                False -&amp;gt; return rectangle
 
mutateRectangle :: Rectangle -&amp;gt; Int -&amp;gt; Int -&amp;gt; IO Rectangle
mutateRectangle (start, end, color) maxX maxY = do possiblyMutatedStart &amp;lt;- maybeMutatePoint start maxX maxY
                                                   possiblyMutatedEnd &amp;lt;- maybeMutatePoint end maxX maxY
                                                   possiblyMutatedColor &amp;lt;- maybeMutateColor color
                                                   return (possiblyMutatedStart, possiblyMutatedEnd, possiblyMutatedColor)
 
maybeNewRectangles :: Int -&amp;gt; Int -&amp;gt; IO [Rectangle]
maybeNewRectangles maxX maxY = do randomNumber &amp;lt;- getStdRandom randomNumberGenerator
                                  case randomNumber &amp;lt; additionProbability of
                                    True -&amp;gt; mapM (\i -&amp;gt; randomRectangle maxX maxY) [1..numberOfAdditions]
                                    False -&amp;gt; return []
mutateDNA :: DNA -&amp;gt; Int -&amp;gt; Int -&amp;gt; IO DNA
mutateDNA (rectangle:rectangles) maxX maxY = do possiblyMutatedRectangle &amp;lt;- maybeMutateRectangle rectangle maxX maxY
                                                possiblyMutatedRectangles &amp;lt;- mutateDNA rectangles maxX maxY
                                                possiblyNewRectangles &amp;lt;- maybeNewRectangles maxX maxY
                                                return $ (possiblyMutatedRectangle : possiblyMutatedRectangles) ++ possiblyNewRectangles
mutateDNA _ _ _ = return []
 
colorDifference :: Color -&amp;gt; Color -&amp;gt; Float
colorDifference color1 color2 = let redDelta = (red color1) - (red color2)
                                    greenDelta = (green color1) - (green color2)
                                    blueDelta = (blue color1) - (blue color2)
                                in sum $ map (** 2.0) [redDelta, greenDelta, blueDelta]
 
comparePixel :: Point -&amp;gt; Map Point Color -&amp;gt; Image -&amp;gt; IO Float
comparePixel point target image = do case lookup point target of
                                       Just color -&amp;gt; do candidateColor &amp;lt;- getPixel point image
                                                        return $ colorDifference color candidateColor
                                       Nothing -&amp;gt; return 0.0
 
fitness :: Map Point Color -&amp;gt; Image -&amp;gt; Int -&amp;gt; Int -&amp;gt; IO Float
fitness target image width height = do deltas &amp;lt;- mapM (\point -&amp;gt; comparePixel point target image)
                                                      [(x, y) | x &amp;lt;- [1..width], y &amp;lt;- [1..height]]
                                       return $ sum deltas
 
printStatus :: Int -&amp;gt; Float -&amp;gt; [Float] -&amp;gt; Int -&amp;gt; IO ()
printStatus iteration fit previousFits objects = do currentTime &amp;lt;- getCurrentTime
                                                    printf &amp;quot;%30s: iteration: %8d, objects: %5d, fit: %14.0f, fit delta: %12.0f, percent improvement: %5.1f%%\n&amp;quot;
                                                           (show currentTime) iteration objects fit delta percentImprovement
 
                                                 where findLastSeenFit [] = 0.0
                                                       findLastSeenFit fits = fits !! (snapshotEvery `mod` (length fits))
 
                                                       lastSeenFit = findLastSeenFit previousFits
                                                       delta = lastSeenFit - fit
                                                       percentImprovement = 100.0 * (delta / lastSeenFit)
 
nextGeneration :: Map Point Color -&amp;gt; Int -&amp;gt; Int -&amp;gt; DNA -&amp;gt; Float -&amp;gt; Int -&amp;gt; IO (DNA, Float)
nextGeneration target width height currentDNA currentFit iteration =
  do case iteration `mod` snapshotEvery of
       0 -&amp;gt; do image &amp;lt;- drawDNAImage width height $ return currentDNA
                       saveJpegFile jpegQuality (&amp;quot;iteration&amp;quot; ++ (show iteration) ++ &amp;quot;.jpg&amp;quot;) image
       otherwise -&amp;gt; return ()
 
     mutatedDNA &amp;lt;- mutateDNA currentDNA width height
     mutatedImage &amp;lt;- drawDNAImage width height $ return mutatedDNA
     mutatedFit &amp;lt;- fitness target mutatedImage width height
 
     case (mutatedFit &amp;lt; currentFit) of
       True -&amp;gt; return (mutatedDNA, mutatedFit)
       False -&amp;gt; return (currentDNA, currentFit)
 
simulationStep :: Map Point Color -&amp;gt; Int -&amp;gt; Int -&amp;gt; DNA -&amp;gt; Int -&amp;gt; Int -&amp;gt; [Float] -&amp;gt; IO [Float]
simulationStep target width height currentDNA iteration totalIterations fits@(currentFit:_)
  | iteration == totalIterations = return fits
  | otherwise = do (nextDNA, nextFit) &amp;lt;- nextGeneration target width height currentDNA currentFit iteration
 
                                      case iteration `mod` snapshotEvery of
                                        0 -&amp;gt; printStatus iteration currentFit fits $ length currentDNA
                                        otherwise -&amp;gt; return ()
 
                                      simulationStep target width height nextDNA (iteration + 1) totalIterations (nextFit:fits)
 
runSimulation :: Map Point Color -&amp;gt; Int -&amp;gt; Int -&amp;gt; DNA -&amp;gt; Int -&amp;gt; IO [Float]
runSimulation target width height ivDNA iterations = simulationStep target width height ivDNA 0 iterations [1e12]
 
main :: IO ()
main = do startTime &amp;lt;- getCurrentTime
          putStrLn $ (show startTime) ++ &amp;quot;: processing started; initial objects = &amp;quot; ++ (show numberOfObjects) ++
                     &amp;quot;, increment = &amp;quot; ++ (show numberOfAdditions) ++
                     &amp;quot;, increment probability = &amp;quot; ++ (show additionProbability) ++
                     &amp;quot;, mutation probability = &amp;quot; ++ (show mutationProbability)
 
          (width, height) &amp;lt;- withImage targetImage imageSize
          target &amp;lt;- targetPixelColors width height
          dna &amp;lt;- initialDNA numberOfObjects width height
          fits &amp;lt;- runSimulation (fromList target) width height dna numberOfIterations
          putStrLn $ show fits&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/735-pseudo-genetic-programming" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor16583</id>
    <published>2008-09-06T20:21:34-07:00</published>
    <title>[Ruby] On Think this needs a loop</title>
    <content type="html">&lt;p&gt;How about this?&lt;/p&gt;

&lt;pre&gt;## helper
def extract source, number, attribute
  (0..(number-1)).inject(Array.new) do |result, index|
    result &amp;lt;&amp;lt; source[index][attribute]
  end
end

## controller 
feed = RssParser.run(&amp;quot;http://ws.audioscrobbler.com/1.0/user/me/recenttracks.rss&amp;quot;)
@songs = extract feed[:items], 3, :title
@links = extract feed[:items], 3, :link

## view
&amp;lt;ul id=&amp;quot;lastfm_update_list&amp;quot;&amp;gt;
	&amp;lt;% @songs.each_with_index do |song, count| %&amp;gt;			
		&amp;lt;li&amp;gt;&amp;lt;%= link_to song, @links[count] %&amp;gt;&amp;lt;/li&amp;gt;
	&amp;lt;% end %&amp;gt;
&amp;lt;/ul&amp;gt;&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/483-think-this-needs-a-loop/refactors/16583" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor13497</id>
    <published>2008-07-21T22:59:27-07:00</published>
    <title>[Ruby] On Dashboard</title>
    <content type="html">&lt;p&gt;I would consider moving the cases into their respective helpers and calling them that way:&lt;/p&gt;

&lt;p&gt;So you would define a method in JobHelper, CandidateHelper, and CommentHelper called activity_message.  Hope this helps,&lt;/p&gt;

&lt;pre&gt;module DashboardHelper

  def activity_message_for object
    &amp;quot;#{object.class.name.classify}Helper&amp;quot;.constantize.send(:activity_message, object)
  end

end&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/392-dashboard/refactors/13497" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor13318</id>
    <published>2008-07-18T23:36:20-07:00</published>
    <title>[Ruby] On Enumerable#cluster</title>
    <content type="html">&lt;p&gt;If you don't need the order preserved and a hash is sufficient...  If you want to keep the ordering, replace with OrderedHash in ActiveSupport (or Ruby 1.9).  cluster_arrayed an implementation that returns an array of arrays.&lt;/p&gt;

&lt;pre&gt;module Enumerable
  def cluster
    inject(Hash.new) do |all, one|
      all[one] = (all[one] || 0) + 1
      all
    end
  end

  def cluster_arrayed
    cluster.inject(Array.new) do |all, (key, count)|
      all &amp;lt;&amp;lt; [key] * count
    end
  end
end
&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/388-enumerable-cluster/refactors/13318" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor13126</id>
    <published>2008-07-15T00:36:49-07:00</published>
    <title>[Ruby] On cleaner way to limit results from xml </title>
    <content type="html">&lt;p&gt;Stream parsing might be something to look into -- &lt;a href="http://www.germane-software.com/software/rexml/docs/tutorial.html#id2248814" target="_blank"&gt;http://www.germane-software.com/software/rexml/docs/tutorial.html#id2248814&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/365-cleaner-way-to-limit-results-from-xml/refactors/13126" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor12859</id>
    <published>2008-07-10T23:20:05-07:00</published>
    <title>[Ruby] On Query String to Hash</title>
    <content type="html">&lt;p&gt;Seems like this should do the job and a little cleaner.&lt;/p&gt;

&lt;pre&gt;Hash[*uri.query.split(&amp;quot;&amp;amp;&amp;quot;).map {|part| part.split(&amp;quot;=&amp;quot;) }.flatten]&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/359-query-string-to-hash/refactors/12859" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor1346</id>
    <published>2008-01-03T17:24:23-08:00</published>
    <title>[Ruby] On Rubyize this : 5th edition</title>
    <content type="html">&lt;p&gt;i purposely wrote this without looking at the refactorings... funny how close it still is but it's a bit different.  a little more verbose imo but extensible.  the only issue i have with it is that you are limited to one a single delimiter.&lt;/p&gt;

&lt;pre&gt;class Highlighter

  def initialize(keywords, prefix='*', suffix='*', delimiter=' ')
    @keywords, @prefix, @suffix, @delimiter = keywords, prefix, suffix, delimiter
  end

  def highlight(text)
    text.split(@delimiter).collect do |word|
      @keywords.include?(word) ? highlight_word(word) : word
    end.join(@delimiter)
  end

  private

  def highlight_word(word)
    @prefix + word + @suffix
  end

end

highlighter = Highlighter.new %w(important monkey dancing)

text = &amp;quot;there are some very important monkeys dancing the most important of all dances in monkey land&amp;quot;
highlighted_text = highlighter.highlight(text)

puts &amp;quot;ORIGINAL   : #{text}&amp;quot;
puts &amp;quot;HIGHLIGHTED: #{highlighted_text}&amp;quot;


&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/203-rubyize-this-5th-edition/refactors/1346" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor1298</id>
    <published>2007-12-30T20:45:33-08:00</published>
    <title>[Ruby] On Creating an alphabetic for search</title>
    <content type="html">&lt;p&gt;I did leave out a piece (the html &amp;lt;&amp;lt; in front of link_to).  What kind of values are you giving to params[:search]?&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/184-creating-an-alphabetic-for-search/refactors/1298" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor1296</id>
    <published>2007-12-30T19:22:05-08:00</published>
    <title>[Ruby] On Creating an alphabetic for search</title>
    <content type="html">&lt;p&gt;Apologies, I wrote this code without testing it ...  Please see the updated helper code and rate if you found it useful.  Thanks!&lt;/p&gt;

&lt;pre&gt;## helper

LETTERS = ('A'..'Z').entries + ['#']

def navigation_links(current_letter)
  returning [] do |html|
    LETTERS.each do |letter|
      if letter == current_letter
        html &amp;lt;&amp;lt; content_tag( :span, letter, :class =&amp;gt; 'current' )
      else
        html &amp;lt;&amp;lt; link_to( letter, :controller =&amp;gt; 'controller', :search =&amp;gt; letter )
      end
    end
  end.join
end&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/184-creating-an-alphabetic-for-search/refactors/1296" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor1208</id>
    <published>2007-12-20T02:04:00-08:00</published>
    <title>[Ruby] On Refactor my blog item helper</title>
    <content type="html">&lt;p&gt;very true :-)&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/187-refactor-my-blog-item-helper/refactors/1208" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor1205</id>
    <published>2007-12-19T18:46:46-08:00</published>
    <title>[Ruby] On Refactor my blog item helper</title>
    <content type="html">&lt;p&gt;I didn't consider sorting in the original refactoring so here's the updated version.  Hope it helps,&lt;/p&gt;

&lt;pre&gt;## Helper

def list_for_blogentries(user)
  blogentries_by_day = user.blogentries.group_by {|entry| entry.created_at.to_date }
  blogentries_sorted_by_day = blogentries_by_day.sort_by {|(date, entries)| date }.reverse
  
  returning &amp;quot;&amp;quot; do |html|
    blogentries_sorted_by_day.each do |date, entries|
      html &amp;lt;&amp;lt; date.to_s
      entries.each {|entry| html &amp;lt;&amp;lt; link_for_entry(entry) }
    end
  end
end&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/187-refactor-my-blog-item-helper/refactors/1205" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor1198</id>
    <published>2007-12-19T13:28:26-08:00</published>
    <title>[Ruby] On Refactor my blog item helper</title>
    <content type="html">&lt;p&gt;See if this works for you.  I would also consider moving the user.blogentries.group_by code into the association proxy -- so you would call user.blogentries.by_day instead.  Check out &amp;quot;Association extensions&amp;quot; here: &lt;a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html" target="_blank"&gt;http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html&lt;/a&gt; for more information.&lt;/p&gt;

&lt;pre&gt;## Helper

def list_for_blogentries(user)
  blogentries_by_day = user.blogentries.group_by {|entry| entry.created_at.to_date }
  
  returning &amp;quot;&amp;quot; do |html|
    blogentries_by_day.each do |date, entries|
      html &amp;lt;&amp;lt; date.to_s
      entries.each {|entry| html &amp;lt;&amp;lt; link_for_entry(entry) }
    end
  end
end&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/187-refactor-my-blog-item-helper/refactors/1198" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor1172</id>
    <published>2007-12-17T00:25:06-08:00</published>
    <title>[Ruby] On Creating an alphabetic for search</title>
    <content type="html">&lt;p&gt;I don't really like having to define a variable inside your view, so I would move the code into a helper.&lt;/p&gt;

&lt;pre&gt;## Helper

LETTERS = ('A'..'Z').entries + ['#']

def navigation_links(current_letter)
  LETTERS.each do |letter|
    if letter == current_letter
      content_tag :span, letter, :class =&amp;gt; 'current'
    else
      link_to letter, :controller =&amp;gt; 'controller', :search =&amp;gt; letter
    end
  end
end

## View [html_rails]

&amp;lt;div class=&amp;quot;pagination&amp;quot;&amp;gt;
  &amp;lt;%= navigation_links params[:search] %&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/184-creating-an-alphabetic-for-search/refactors/1172" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor982</id>
    <published>2007-11-28T17:23:16-08:00</published>
    <title>[Ruby] On split_in_groups instead of in_groups_of</title>
    <content type="html">&lt;p&gt;here's my first shot at it&lt;/p&gt;

&lt;pre&gt;##code [ruby]

class Array

  def in_uniform_groups_of(group_count)
    answer = Array.new
    index = 0

    self.class.uniform_partition_sizes(self.size, group_count).each do |size|
      answer &amp;lt;&amp;lt; self.slice( index, size )
      index += size
    end

    answer
  end

  def self.uniform_partition_sizes(size, partitions)
    answer = Array.new( partitions, size / partitions )

    index = 0
    total = (size / partitions) * partitions

    while total &amp;lt; size
      answer[index] += 1
      index = (index + 1) % partitions
      total += 1
    end

    answer
  end

end

puts (1..9).to_a.in_uniform_groups_of(4).inspect
puts (1..10).to_a.in_uniform_groups_of(4).inspect&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/167-split_in_groups-instead-of-in_groups_of/refactors/982" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor867</id>
    <published>2007-11-16T13:16:13-08:00</published>
    <title>[Ruby] On Simple Text Replacement</title>
    <content type="html">&lt;p&gt;I agree with Scott about making the first argument to gsub! a string rather than a hash and I also agree with not using send (or eval).  However, I also think that you should DRY up the hash by removing the curly braces.  So, to add onto Scott's code:&lt;/p&gt;

&lt;p&gt;About the common courtesies, I would say rate them and leave comments for the refactorers.&lt;/p&gt;

&lt;pre&gt;def replace_keywords(keywords, text)
  keywords.each do |keyword, replacement|
    text.gsub! &amp;quot;\{#{keyword}\}&amp;quot;, replacement
  end

  text
end

keywords = { 'city' =&amp;gt; 'Chicago', 'state' =&amp;gt; 'Illinois' }
text = &amp;quot;Welcome to {city}, {state}&amp;quot;

puts replace_keywords(keywords, text)&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/155-simple-text-replacement/refactors/867" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor863</id>
    <published>2007-11-16T03:18:31-08:00</published>
    <title>[Ruby] On Simple Text Replacement</title>
    <content type="html">&lt;p&gt;How about this?&lt;/p&gt;

&lt;pre&gt;def replace_keywords(keywords, text)
  keywords.each do |keyword, replacement|
    text.send( 'gsub!', &amp;quot;\{#{keyword}\}&amp;quot;, &amp;quot;#{replacement}&amp;quot; )
  end

  text
end

keywords = { 'city' =&amp;gt; 'Chicago', 'state' =&amp;gt; 'Illinois' }
text = &amp;quot;Welcome to {city}, {state}&amp;quot;

puts replace_keywords(keywords, text)
&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/155-simple-text-replacement/refactors/863" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor814</id>
    <published>2007-11-10T02:06:37-08:00</published>
    <title>[Ruby] On Circular Cipher</title>
    <content type="html">&lt;p&gt;The original and most of these refactorings fail if the key length is less than the message length.&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/138-circular-cipher/refactors/814" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor779</id>
    <published>2007-11-07T03:46:40-08:00</published>
    <title>[Ruby] On Circular Cipher</title>
    <content type="html">&lt;p&gt;this code will be much cleaner in Ruby 1.9 when we get external iterators.... but, i formed the code into a class, cleaned up the math a bit, and made the cipher reuse the key if the string to be encoded/decoded is longer than the key.  i also added a very simple spec (using RSpec)&lt;/p&gt;

&lt;pre&gt;## class [ruby]

class Cipher

        Offset = ?\  # ascii value of a space
        Range = ?z - ?\ # difference between ascii values for z and space

        def initialize(key)
                @key = key
                @key_length = key.size
        end

        def encode( clear_text )
                cipher_text = String.new
                index = 0

                clear_text.each_byte do |byte|
                        cipher_text &amp;lt;&amp;lt; (byte + @key[index % @key_length] - 2*Offset) % Range + Offset
                        index += 1
                end

                cipher_text
        end

        def decode( cipher_text )
                clear_text = String.new
                index = 0;

                cipher_text.each_byte do |byte|
                        clear_text &amp;lt;&amp;lt; (byte - @key[index % @key_length] + Range) % Range + Offset
                        index += 1
                end

                clear_text
        end

end

## spec [ruby]

require 'cipher'

describe Cipher, &amp;quot;with a sufficient key size&amp;quot; do

        before do
                @cipher = Cipher.new( &amp;quot;s7eOhg2fqgPRWXtp303B67551G5zpEyHe78q5NR5eWKP9eq9fk54D23&amp;quot; )
        end


        it &amp;quot;should correctly encode a string&amp;quot; do
                @cipher.encode( &amp;quot;I wonder if this code can be better.&amp;quot; ).should == 'B7bD\Qw^qV&amp;lt;RQFci3s(,!7xv%Gwep-dB_&amp;quot;0%'

        end

        it &amp;quot;should correctly decode a string&amp;quot; do
                @cipher.decode( 'B7bD\Qw^qV&amp;lt;RQFci3s(,!7xv%Gwep-dB_&amp;quot;0%' ).should == &amp;quot;I wonder if this code can be better.&amp;quot;
        end

end

describe Cipher, &amp;quot;without a sufficient key size&amp;quot; do

        before do
                @cipher = Cipher.new( &amp;quot;s3EHqP9f23&amp;quot; )
        end


        it &amp;quot;should correctly encode a string&amp;quot; do
                @cipher.encode( &amp;quot;I wonder if this code can be better.&amp;quot; ).should == &amp;quot;B3B=e:$^2\&amp;quot;_3?6`I9O'w^3./eP!Q2u^-?3i^&amp;quot;

        end

        it &amp;quot;should correctly decode a string&amp;quot; do
                @cipher.decode( &amp;quot;B3B=e:$^2\&amp;quot;_3?6`I9O'w^3./eP!Q2u^-?3i^&amp;quot; ).should == &amp;quot;I wonder if this code can be better.&amp;quot;
        end

end
&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/138-circular-cipher/refactors/779" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor442</id>
    <published>2007-10-16T23:25:02-07:00</published>
    <title>[Ruby] On Combining add/remove links</title>
    <content type="html">&lt;p&gt;I don't see where you use the argument to these functions.... Anyway, here's my shot at refactoring&lt;/p&gt;

&lt;pre&gt;  def add_associated_link(model_name, label = &amp;quot;Add another&amp;quot;)
    link_to_function label do |page|
    	page.insert_html :bottom, model_name.pluralize, :partial =&amp;gt; model_name, :object =&amp;gt; model_name.camelize.constantize.new
    end
  end
  
  def remove_associated_link(model_name, label = &amp;quot;Remove&amp;quot;)
    link_to_function label {|page| page[&amp;quot;#{model_name}_#{params[:index]}&amp;quot;].remove }
  end&lt;/pre&gt;</content>
    <author>
      <name>Jason Dew</name>
      <email>jason.dew@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/89-combining-add-remove-links/refactors/442" rel="alternate"/>
  </entry>
</feed>

