<?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:users1969friends</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/1969/friends" rel="self"/>
  <title>paulhomebus friends</title>
  <updated>Tue Apr 21 23:24:52 -0700 2009</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code835</id>
    <published>2009-04-21T23:24:52-07:00</published>
    <updated>2009-04-23T14:14:23-07:00</updated>
    <title>[C] Polymorphic functions using pointers to pointers</title>
    <content type="html">&lt;p&gt;The *stupid* example below expresses what I wish to accomplish in terms of functionality. When I change OBJ in Animal_inspect's signature to Dog, and then cast both animals as Dogs (removing (*animal)-&amp;gt;name) everything is fine, however ideally I would like a pointer of a pointer to be passed, but the compiler complains&lt;/p&gt;

&lt;pre&gt;#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;stdlib.h&amp;gt;

#define ALLOC(x) (x) malloc(sizeof(struct _##x))

typedef int *OBJ;

enum {
  tDog,
  tCat
};

typedef struct _Cat {
  int type;  
  char *name;  
} *Cat;

typedef struct _Dog {
  int type;
  char *name;
} *Dog;

Cat
Cat_alloc() {
  return ALLOC(Cat);
}

Dog
Dog_alloc() {
  return ALLOC(Dog);
}

Cat
Cat_new(char *name) {
  Cat cat = Cat_alloc();
  cat-&amp;gt;type = tCat;
  cat-&amp;gt;name = name;
  return cat;
}

Dog
Dog_new(char *name) {
  Dog dog = Dog_alloc();
  dog-&amp;gt;type = tDog;
  dog-&amp;gt;name = name;
  return dog;
}

void
Animal_inspect(OBJ self) {
  printf(&amp;quot;&amp;lt;Animal name:%s&amp;gt;\n&amp;quot;, (*self)-&amp;gt;name);
}

int
main(int argc, char **argv) {
  Dog dog = Dog_new(&amp;quot;Fatty&amp;quot;);
  Cat cat = Cat_new(&amp;quot;Fluffy&amp;quot;);
  
  Animal_inspect((OBJ) cat);
  Animal_inspect((OBJ) dog);
  
  return 0;
}
&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/835-polymorphic-functions-using-pointers-to-pointers" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code821</id>
    <published>2009-04-13T01:03:01-07:00</published>
    <updated>2009-04-13T15:13:36-07:00</updated>
    <title>[Haskell] Tag</title>
    <content type="html">&lt;p&gt;Just playing around, super new to Haskell (1 hour or so), and pointers would be great&lt;/p&gt;

&lt;pre&gt;
---
--- Tag
---

data Tag = Tag {
 tagType  :: String,
 tagAttrs :: [Attr]
}

data Attr = Attr String String

---
--- tagToHTML
---

tagToHTML :: Tag -&amp;gt; String
tagToHTML t = &amp;quot;&amp;lt;&amp;quot; ++ tagType t ++ &amp;quot; &amp;quot; ++ attrs ++ &amp;quot;/&amp;gt;a&amp;quot;
          where attrs = join (map attrPair (tagAttrs t))

---
--- attrPair
---

attrPair :: Attr -&amp;gt; String
attrPair (Attr k v) = k ++ &amp;quot;=\&amp;quot;&amp;quot; ++ v ++ &amp;quot;\&amp;quot;&amp;quot;

---
--- join
---

join :: [String] -&amp;gt; String 
join (x:xs) = x ++ &amp;quot; &amp;quot; ++ (join xs)
join [] = &amp;quot;&amp;quot;

--- main

input = Tag &amp;quot;input&amp;quot; [Attr &amp;quot;id&amp;quot; &amp;quot;comments&amp;quot;, Attr &amp;quot;disabled&amp;quot; &amp;quot;disabled&amp;quot;]
main = print (tagToHTML input)&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/821-tag" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code820</id>
    <published>2009-04-11T19:26:44-07:00</published>
    <updated>2009-04-11T19:26:44-07:00</updated>
    <title>[JavaScript] Testing Framework</title>
    <content type="html">&lt;p&gt;Snippit from &lt;a href="http://visionmedia.github.com/jspec/" target="_blank"&gt;http://visionmedia.github.com/jspec/&lt;/a&gt;, trying to come up with the most readable syntax possible for the testing framework (-{} is alternative for function(){} )&lt;/p&gt;

&lt;pre&gt;describe 'ShoppingCart'
  var cart

  before_each
    cart = new ShoppingCart
  end
  
  describe 'addProducts'
    it 'should add several products'
      cart.addProduct('cookie')
      cart.addProduct('icecream')
      cart.should.have 2, 'products'
    end
  end

  describe 'checkout'
    it 'throw an error when checking out with no products'
      -{ cart.clear().checkout() }.should.throw_error
    end
  end
end&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/820-testing-framework" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code817</id>
    <published>2009-04-08T21:26:25-07:00</published>
    <updated>2009-04-08T21:48:31-07:00</updated>
    <title>[Ruby] Hash#switchify</title>
    <content type="html">&lt;p&gt;Whipped this up really quick, the output shows what I want but pretty messy IMO&lt;/p&gt;

&lt;pre&gt;
class String
  def dasherize
    to_s.gsub '_', '-'
  end
  
  def switchify
    length &amp;gt; 1 ? &amp;quot;--#{dasherize}&amp;quot; : &amp;quot;-#{self}&amp;quot;
  end
end

class Hash
  def switchify
    inject [] do |args, (key, value)|
      next args unless value
      args &amp;lt;&amp;lt; key.to_s.switchify
      args &amp;lt;&amp;lt; (value === String ? value.inspect : value.to_s) unless value === true
      args
    end
  end
end

h = { :config =&amp;gt; 'foo.ini', :verbose =&amp;gt; true, :with_foo_bar =&amp;gt; false, :with_some_coolness =&amp;gt; true, :T =&amp;gt; true }

p h.switchify
# =&amp;gt; [&amp;quot;--config&amp;quot;, &amp;quot;foo.ini&amp;quot;, &amp;quot;--verbose&amp;quot;, &amp;quot;--with-foo&amp;quot;, &amp;quot;-T&amp;quot;]

p h.switchify.join(' ')
# =&amp;gt; --config foo.ini --verbose --with-foo -T&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/817-hash-switchify" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code793</id>
    <published>2009-03-20T18:35:48-07:00</published>
    <updated>2009-12-23T04:03:01-08:00</updated>
    <title>[Ruby] Simple wrap method</title>
    <content type="html">&lt;p&gt;rawr&lt;/p&gt;

&lt;pre&gt;class String
  def wrap prefix, suffix = nil
    [prefix, self, (suffix || prefix)].join
  end
end

puts 'foo'.wrap('|') 
# =&amp;gt; |foo|

puts 'foo'.wrap('(', ')')
# =&amp;gt; (foo)&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/793-simple-wrap-method" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code791</id>
    <published>2009-03-17T21:26:41-07:00</published>
    <updated>2009-03-18T00:42:25-07:00</updated>
    <title>[JavaScript] Range</title>
    <content type="html">&lt;p&gt;I use this in a JS interpreted grammar for JSpec, if anyone has a better solution let me know :D&lt;/p&gt;

&lt;pre&gt;/**
 * Create a range string which can be evaluated to a native array.
 *
 * @param  {int} start
 * @param  {int} end
 * @return {string}
 * @api public
 */

function range(start, end) {
  s = parseInt(start), e = parseInt(end), b = '[' + s
  if (e &amp;gt; s) while (++s &amp;lt;= e) b += ',' + s
  else       while (--s &amp;gt;= e) b += ',' + s
  return b + ']'
}&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/791-range" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code763</id>
    <published>2009-02-21T01:08:10-08:00</published>
    <updated>2009-02-28T07:42:23-08:00</updated>
    <title>[Ruby] String#strip with char list</title>
    <content type="html">&lt;p&gt;Better way?&lt;/p&gt;

&lt;pre&gt;class String
  def strip chars = &amp;quot;\s&amp;quot;
    gsub /^[#{chars}]+|[#{chars}}]+$/, ''
  end
end

p ' test '.strip        # =&amp;gt; &amp;quot;test&amp;quot;
p '$test$'.strip('$')   # =&amp;gt; &amp;quot;test&amp;quot;
p '&amp;lt;test&amp;gt;'.strip('&amp;lt;&amp;gt;')  # =&amp;gt; &amp;quot;test&amp;quot;
p '.test.'.strip('.')   # =&amp;gt; &amp;quot;test&amp;quot;&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/763-string-strip-with-char-list" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code734</id>
    <published>2009-02-02T18:34:25-08:00</published>
    <updated>2009-02-02T18:38:31-08:00</updated>
    <title>[Ruby] Time lost since </title>
    <content type="html">&lt;p&gt;Pasted the rest just so people can play around, but #lost_since is the only thing Im concerned about, the lambda needs some loven&lt;/p&gt;

&lt;pre&gt;require 'rubygems'

class Numeric
  
  def second ; self * 1 end
  alias_method :seconds, :second
  
  def minute; self * 60 end
  alias_method :minutes, :minute
  
  def hour; self * 3600 end
  alias_method :hours, :hour
  
  def day; self * 86400 end
  alias_method :days, :day
  
  def week; self * 604800 end
  alias_method :weeks, :week
  
  def month; self * 2592000 end
  alias_method :months, :month
  
  def year; self * 31471200 end
  alias_method :years, :year
  
  def to_minutes; self / 1.minute end
  def to_hours;   self / 1.hour   end
  def to_days;    self / 1.day    end
  def to_weeks;   self / 1.weeks  end
  def to_months;  self / 1.months end
  def to_years;   self / 1.years  end
  
end

module TimeHelpers
  def lost_since time = Time.now
    return unless self &amp;lt; time
    seconds = (time - self).to_i
    pluralize = lambda { |string| n = seconds.send(:&amp;quot;to_#{string}s&amp;quot;); n == 1 ? &amp;quot;one #{string}&amp;quot; : &amp;quot;#{n} #{string}s&amp;quot; }
    case seconds
    when 0..59                ; &amp;quot;less than one minute&amp;quot;
    when 1.minute..59.minutes ; pluralize[:minute]
    when 1.hour..23.hours     ; pluralize[:hour]
    when 1.day..6.days        ; pluralize[:day]
    when 1.week..3.weeks      ; pluralize[:week]
    when 1.month..11.months   ; pluralize[:month]
    when 1.year..4.years      ; pluralize[:year]
    else &amp;quot;several years&amp;quot;
    end
  end
  alias :lost_since_now :lost_since
end

Time.send :include, TimeHelpers

describe &amp;quot;#lost_since&amp;quot; do
  it &amp;quot;should return nil when greater than now&amp;quot; do
    event = Time.now + 5.days
    event.lost_since_now.should be_nil
  end
  
  it &amp;quot;should return less than one minute&amp;quot; do
    event = Time.now - 30.seconds
    event.lost_since_now.should == 'less than one minute'
  end
  
  %w( minutes hours days weeks months years ).each do |v|
    it &amp;quot;should return several #{v}&amp;quot; do
      event = Time.now - 2.send(v)
      event.lost_since_now.should == &amp;quot;2 #{v}&amp;quot;
    end
  end
  
  %w( minute hour day week month year ).each do |v|
    it &amp;quot;should return a single #{v}&amp;quot; do
      event = Time.now - 1.send(v)
      event.lost_since_now.should == &amp;quot;one #{v}&amp;quot;
    end
  end
  
  it &amp;quot;should return several years when past 4&amp;quot; do
    event = Time.now - 5.years
    event.lost_since_now.should == &amp;quot;several years&amp;quot;
  end
  
  it &amp;quot;should work using alternate time as argument&amp;quot; do
    event = Time.now - 10.days
    event2 = Time.now - 5.days
    event.lost_since(event2).should == '5 days'
  end
  
  it &amp;quot;should work using future time as argument&amp;quot; do
    # Not sure when anyone would do this ... but it works
    event = Time.now - 7.days
    event2 = Time.now + 7.days
    event.lost_since(event2).should == '2 weeks'
  end
  
end

&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/734-time-lost-since" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code714</id>
    <published>2009-01-23T20:13:31-08:00</published>
    <updated>2010-01-25T22:42:41-08:00</updated>
    <title>[Ruby] Recursive population of hash key-value pairs</title>
    <content type="html">&lt;p&gt;I do not even know where to begin on this one to be honest. Basically I want to parse a string, for example a query string, and populate a hash. Parsing the query string is super easy I am just not sure how to dynamically populate the hash in Ruby. In PHP I know this was a limitation (among many haha..) and you had to support X levels of nesting&lt;/p&gt;

&lt;pre&gt;params[:name][:primary] # etc ...&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/714-recursive-population-of-hash-key-value-pairs" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code701</id>
    <published>2009-01-09T20:14:40-08:00</published>
    <updated>2009-01-10T17:29:40-08:00</updated>
    <title>[Ruby] Closure scoping issue</title>
    <content type="html">&lt;p&gt;Below is the syntax I would like. However the only problem I am running into is that even when #form uses a proxy object to redirect method calls to my Elements module, the instance evaluation of the block below still call the methods at the global scope, in turn not 'collecting' results of each invocation. I know I could simply pass an object to the block like the second example but I would way rather have it this way&lt;/p&gt;

&lt;pre&gt;   
  include Form::Elements

  form :login do
    textfield :name, :label =&amp;gt; 'Username'
    textfield :pass, :label =&amp;gt; 'Password'
    submit :op, :value =&amp;gt; 'Login'
  end

  form :login do |f|
    f.textfield :name, :label =&amp;gt; 'Username'
    f.textfield :pass, :label =&amp;gt; 'Password'
    f.submit :op, :value =&amp;gt; 'Login'
  end
&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/701-closure-scoping-issue" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code695</id>
    <published>2009-01-05T21:14:49-08:00</published>
    <updated>2009-01-12T02:35:52-08:00</updated>
    <title>[Ruby] includes_all?</title>
    <content type="html">&lt;p&gt;Having brain cramps today, this implementation could certainly be better. It is somewhat ad-hoc, I needed it for a permission system but figured I would abstract it a little&lt;/p&gt;

&lt;pre&gt;require 'ostruct'
require 'rubygems'
require 'extlib/blank'

class Object
  def includes_all? objects, options = {}
    meth = options.delete :method
    enum = (meth and respond_to? meth) ? self.send(meth) : self
    objects.each do |v|
      return false unless enum.include? v
    end
    true
  end
end

describe &amp;quot;includes_all?&amp;quot; do
  it &amp;quot;should work with flat arrays&amp;quot; do
    ['hey', 'there', 'world'].includes_all?(['hey', 'there']).should be_true
  end
  
  it &amp;quot;should work with arbitrary objects&amp;quot; do
    obj = { :foo =&amp;gt; 'bar' }
    [1, 'two', obj].includes_all?([obj, 1]).should be_true
  end
  
  it &amp;quot;should fail appropriately&amp;quot; do
    ['foo', 'bar'].includes_all?(['foo', 'fail']).should be_false
    ['foo', 'bar'].includes_all?([]).should_not be_false
  end
  
  it &amp;quot;should work with methods&amp;quot; do
    role = OpenStruct.new
    role.permissions = ['access content', 'edit content']
    role.includes_all?(['access content', 'edit content'], :method =&amp;gt; :permissions).should be_true
    role.includes_all?(['delete content'], :method =&amp;gt; :permissions).should be_false
  end
end&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/695-includes_all" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code671</id>
    <published>2008-12-16T21:30:54-08:00</published>
    <updated>2008-12-18T05:08:43-08:00</updated>
    <title>[Ruby] Run once</title>
    <content type="html">&lt;p&gt;Cleaner way?&lt;/p&gt;

&lt;pre&gt;def run_once &amp;amp;block
  path = File.expand_path caller.first
  unless ($__run_once ||= []).include? path
    yield
    $__run_once &amp;lt;&amp;lt; path
  end
end&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/671-run-once" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code666</id>
    <published>2008-12-12T23:20:50-08:00</published>
    <updated>2009-01-15T22:45:36-08:00</updated>
    <title>[Ruby] Proc param names</title>
    <content type="html">&lt;p&gt;Below is the exact result I want, just the param names, however I need to do this without explicitly returning the binding, can this be done without a bunch of 'meta-magic'?&lt;/p&gt;

&lt;pre&gt;
# Working example
def test &amp;amp;block
  bind = yield 1, 2, 3
  p eval('local_variables', bind)
end

test do |just, some, params|
  binding
end

# =&amp;gt; ['just', 'some', 'params']&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/666-proc-param-names" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code618</id>
    <published>2008-11-22T06:16:53-08:00</published>
    <updated>2008-11-22T15:48:37-08:00</updated>
    <title>[Ruby] Bindings on caller</title>
    <content type="html">&lt;p&gt;I dont really have a need for this but i was trying to figure it out and was curious this sort of thing could be accomplished with bindings.&lt;/p&gt;

&lt;pre&gt;def test(a, b)
  capitalize_args
  puts a   # =&amp;gt; Hello
  puts b   # =&amp;gt; World
end

test &amp;quot;hello&amp;quot;, &amp;quot;world&amp;quot;&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/618-bindings-on-caller" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code617</id>
    <published>2008-11-22T02:27:39-08:00</published>
    <updated>2008-12-08T11:39:37-08:00</updated>
    <title>[Ruby] Initial script execution very slow and skewing results</title>
    <content type="html">&lt;p&gt;Below is a little snippit of a quick response time monitor I was playing around with, works fine BUT when executed the first time everything performs really slowly and skews the duration by 3 to 4 seconds.. after that every execution works as expected.&lt;/p&gt;

&lt;pre&gt;def monitor(uri)
  Thread.new(uri) do |uri|
    begin
      start = Time.now
      res = open uri
      duration = (Time.now - start).abs
      puts &amp;quot;   %0.3f | %s | %s&amp;quot; % [duration, res.status.join(' '), uri]
    rescue
      puts &amp;quot;   0.000 | 404 Not Found | %s&amp;quot; % [uri]
    end
  end.queue
end&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/617-initial-script-execution-very-slow-and-skewing-results" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code616</id>
    <published>2008-11-22T02:16:09-08:00</published>
    <updated>2008-11-22T02:16:09-08:00</updated>
    <title>[Ruby] suppress ERB newlines</title>
    <content type="html">&lt;p&gt;Just plain-jane ERB. What does rails do differently to allow &amp;lt;% -%&amp;gt; and &amp;lt;%= -%&amp;gt; ? to get below to actually format correctly I have to place the erb tags in a gross manor.. initializing ERB with &amp;lt;&amp;gt; or &amp;gt;&lt;/p&gt;

&lt;pre&gt;
  NAME:
  
    &amp;lt;%= @name %&amp;gt;
  
  DESCRIPTION:
  
    &amp;lt;%= @description %&amp;gt;
  
  SYNOPSIS:
  
    &amp;lt;%= @syntax %&amp;gt;

&amp;lt;% unless @examples.empty? %&amp;gt;
  EXAMPLES:
  &amp;lt;% @examples.each do |example| %&amp;gt;  
    # &amp;lt;%= example[:description] %&amp;gt;
    &amp;lt;%= example[:command] %&amp;gt;
  &amp;lt;% end %&amp;gt;
&amp;lt;% end %&amp;gt; 

&amp;lt;% unless @options.empty? %&amp;gt;
  OPTIONS:
  &amp;lt;% @options.each do |option| %&amp;gt;
    &amp;lt;%= option[:args].join(', ') %&amp;gt;
  &amp;lt;% end %&amp;gt;
&amp;lt;% end %&amp;gt;

&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/616-suppress-erb-newlines" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code609</id>
    <published>2008-11-19T05:23:59-08:00</published>
    <updated>2008-11-19T18:11:23-08:00</updated>
    <title>[Ruby] Caching Methods</title>
    <content type="html">&lt;p&gt;Is it possible to cache methods in a manor similar to below? (non-RoR). I have a few ideas of how this may work but any suggestions would be great&lt;/p&gt;

&lt;pre&gt;
class Something
  
  def something_else
    &amp;quot;Expensive operation&amp;quot;
  end
  
  cache_method :something_else, :for =&amp;gt; 2.hours
  
end

inst = Something.new

# Empty cache
inst.something_else

# Primed cache
inst.something_else&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/609-caching-methods" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code556</id>
    <published>2008-10-23T22:25:19-07:00</published>
    <updated>2008-10-24T18:31:21-07:00</updated>
    <title>[Ruby] Yield by 'reference'</title>
    <content type="html">&lt;p&gt;This has been bugging me, its a simple thing but I do not quite understand how &amp;quot;initial&amp;quot; and &amp;quot;total_length&amp;quot; have the same object_id, and yet the example below will not work.&lt;/p&gt;

&lt;p&gt; Ps. this is not an actually implementation I just needed a similar use so this was the test code&lt;/p&gt;

&lt;pre&gt;class Array
  def new_inject(initial, &amp;amp;block)
    self.each { |v| yield initial, v } 
    initial
  end
end

p %w[ just a test ].new_inject(0) { |total_length, v| total_length += v.length }&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/556-yield-by-reference" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code508</id>
    <published>2008-09-26T03:04:52-07:00</published>
    <updated>2008-09-26T22:58:16-07:00</updated>
    <title>[Ruby] Source code analysis</title>
    <content type="html">&lt;p&gt;Small class to analyze scripts, outputs similar to below:&lt;/p&gt;

&lt;p&gt;files js 5
&lt;br /&gt;declared classes 146
&lt;br /&gt;lines todo 27
&lt;br /&gt;lines blank 3171
&lt;br /&gt;files 69
&lt;br /&gt;lines 28263
&lt;br /&gt;files module 3
&lt;br /&gt;files inc 36
&lt;br /&gt;files install 1
&lt;br /&gt;files css 5
&lt;br /&gt;files php 19
&lt;br /&gt;declared functions 1004
&lt;br /&gt;lines comments 6313
&lt;br /&gt;comment ratio 0.22&lt;/p&gt;

&lt;p&gt;I dont really like the order of which I am outputting but you cannot sort Hashes correct? it looks fine
&lt;br /&gt;when piped through sort $ lc -r . | sort -n, but I would hardly call that ideal. Anyways feel free to comment
&lt;br /&gt;or refactor any portion, I am eager to learn Ruby and seeing your examples helps alot!&lt;/p&gt;

&lt;pre&gt;#!/usr/bin/env ruby

# == Synopsis
#   lc is an open source Ruby program for analysing the contents
#   of source code, such as line counts and comment ratios.
#
# == Usage
#   lc [-hVr] [ dir | file ... ]
#  
# == Examples
#   Analyse current directory 
#     lc
#    
#   Analyse current directory recursively
#     lc --recursive
#    
#   Analyse specific files and a directory recursively
#     lc -r ./index.php ./cron.php ./sites/all/modules/gui
#    
# == Options
#   -h, --help      Display this help information.
#   -V, --version   Display version of lc.
#   -r, --recurse   Scan directories recursively.
# 
# == Author
#   TJ Holowaychuk 
#
# == Copyright
#   Copyright (c) 2008 TJ Holowaychuk. Licensed under the MIT License:
#   http://www.opensource.org/licenses/mit-license.php

require 'optparse'
require 'rdoc/usage'
	
$syntax = {
		'rb' =&amp;gt; {																																						
				:name =&amp;gt; 'Ruby',																																
				:blank =&amp;gt; /^\s*$/,																															
				:comment =&amp;gt; /^[\s]*#/,																													
				:comment_open =&amp;gt; /[\s]*=begin/,																									
				:comment_close =&amp;gt; /[\s]*=end/,																									
				:function =&amp;gt; /def[\s]+[\w]+/,																										
				:class =&amp;gt; /class[\s]+[\w]+/,			
				:todo =&amp;gt; /@?todo/,																							
				:associations =&amp;gt; ['rb', 'erb']																									
			},																																								
		'php' =&amp;gt; {																																					
				:name =&amp;gt; 'PHP',																																	
				:blank =&amp;gt; /^\s*$/,																															
				:comment =&amp;gt; /^[\s]*\/\//,																												
				:comment_open =&amp;gt; /^[\s]*\/\*/,																									
				:comment_close =&amp;gt; /[\s]*\*\//,																									
				:function =&amp;gt; /^[\s]*function[\s]+[\w]+[\s]*\(/,																				
				:class =&amp;gt; /class[\s]+[\w]+/,												
				:todo =&amp;gt; /@?todo/,														
				:associations =&amp;gt; ['php', 'inc', 'module', 'install']														
			},																																								
		'js' =&amp;gt; {																																						
				:name =&amp;gt; 'JavaScript',																													
				:blank =&amp;gt; /^\s*$/,																															
				:comment =&amp;gt; /^[\s]*\/\//,																												
				:comment_open =&amp;gt; /^[\s]*\/\*/,																									
				:comment_close =&amp;gt; /[\s]*\*\//,																									
				:function =&amp;gt; /^[\s]*(?:function[\s][\w]+|(var)?[\s]*[\w\.]+[\s]+=[\s]+function)[\s]*\(/,	
				:todo =&amp;gt; /@?todo/,
				:associations =&amp;gt; ['js']																													
			},																																								
		'css' =&amp;gt; {																																					
				:name =&amp;gt; 'CSS',																																	
				:blank =&amp;gt; /^\s*$/,																															
				:comment =&amp;gt; /^[\s]*\/\//,																												
				:comment_open =&amp;gt; /^[\s]*\/\*/,																									
				:comment_close =&amp;gt; /[\s]*\*\//,						
				:todo =&amp;gt; /@?todo/,																																			
				:associations =&amp;gt; ['css']																												
			}																																									
	}																																											

class LC 
	
	VERSION = '0.0.1'
	
	attr_reader :files, :reports
	attr_accessor :options, :arguments
	
	# Initialize
	def initialize()
		self.initialize_options
		self.initialize_reports
	end
	
	# Initialize option defaults
	def initialize_options
		@options = {}
		@options[:recursive] = false		
	end
	
	# Initialize reports, create defaults
	def initialize_reports
		@reports = {}
		@reports[:comment_ratio] = 0
		@reports[:totals] = {
		    'files' =&amp;gt; 0,
		    'lines' =&amp;gt; 0,
				'lines blank' =&amp;gt; 0,
				'lines comments' =&amp;gt; 0,
				'lines todo' =&amp;gt; 0,
				'declared functions' =&amp;gt; 0,
				'declared classes' =&amp;gt; 0,			 
			}
		$syntax.each do |lang|
			lang[1][:associations].each do |association|
				@reports[:totals]['files ' &amp;lt;&amp;lt; association] = 0
			end
		end		 
	end
	
	# Start analysis.
	def run
		# Parse options
		self.parse_options
		
		# Default files to cwd
		@files = @arguments.empty? ? ['.'] : @arguments

		# Parse files and directories
		file_pattern = $syntax.collect{|lang| lang[1][:associations].join(',')}.join(',')
		@files.each do |file|
			if File.directory?(file)
				files = Dir[(@options[:recursive] ? '**/' : '') &amp;lt;&amp;lt; file &amp;lt;&amp;lt; '/*.{' + file_pattern + '}']
				files.each do |file|
					self.parse_script(file)
				end			 
			elsif File.file?(file)
				self.parse_script(file)
			end
		end

		# Report
		self.prep_report
		self.output_report
		exit
	end
	
	# Parse options
	def parse_options
		opts = OptionParser.new
		opts.on('-h', '--help')				{ RDoc.usage(0) }
		opts.on('-V', '--version')		{ self.output_version; exit 0 }
		opts.on('-r', '--recursive')	{ @options[:recursive] = true }
		begin
		  opts.parse!(@arguments)
	  rescue =&amp;gt; e
	    puts e
	    exit 1
    end
	end

	# Get extension of filepath.
	def get_extension(filepath) 
		File.extname(filepath).reverse.chop.reverse
	end

	# Get syntax based on a filenames extension.
	def get_syntax(filepath)
		extension = get_extension(filepath)
		$syntax.each_pair do |lang, info|
			return $syntax[lang] if info[:associations].include?(extension)
		end
	end

	# Parse a script and report on findings.
	def parse_script(filepath)
		lang = get_syntax(filepath)
		comment_open = false
		extension = get_extension(filepath)

		# Ensure syntax was found
		if lang.kind_of? NilClass
			return
		end

		File.open(filepath) do |file| 
			@reports[:totals]['files'] += 1
			@reports[:totals]['files ' &amp;lt;&amp;lt; extension] += 1
			file.each_line do |line|
				@reports[:totals]['lines'] += 1
				@reports[:totals]['lines blank'] += 1 if line.match(lang[:blank])
				if !line.match(lang[:blank])
				  @reports[:totals]['lines todo'] += 1 if line.match(lang[:todo])
				  case 
			      when line.match(lang[:comment]); @reports[:totals]['lines comments'] += 1 
			      when line.match(lang[:comment_open]); @reports[:totals]['lines comments'] += 1; comment_open = true
			      when line.match(lang[:comment_close]); @reports[:totals]['lines comments'] += 1; comment_open = false
            else 
						  if comment_open
							  @reports[:totals]['lines comments'] += 1
						  else
						    case
					        when lang[:function] &amp;amp;&amp;amp; line.match(lang[:function]); @reports[:totals]['declared functions'] += 1
							    when lang[:class] &amp;amp;&amp;amp; line.match(lang[:class]); @reports[:totals]['declared classes'] += 1
							  end
						  end
					end
				end
			end
		end
	end

	# Prepare output of report.
	def prep_report
		if @reports[:totals]['lines comments'] &amp;gt; 0 and @reports[:totals]['lines'] &amp;gt; 0
			@reports[:comment_ratio] = @reports[:totals]['lines comments'].to_f / @reports[:totals]['lines'].to_f 
		end
	end

	# Output report.
	def output_report
		@reports[:totals].each_pair do |k, v| 
			puts k + ' ' + v.to_s unless v == 0
		end
		puts 'comment ratio ' &amp;lt;&amp;lt; '%.2f' % @reports[:comment_ratio] unless @reports[:comment_ratio] == 0
	end
	
	# Output version information.
	def output_version
		puts &amp;quot;Version #{LC::VERSION}&amp;quot;
	end
end

counter = LC.new
counter.arguments = ARGV
counter.run

&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/508-source-code-analysis" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code504</id>
    <published>2008-09-23T16:06:20-07:00</published>
    <updated>2008-09-24T17:57:32-07:00</updated>
    <title>[Ruby] Interactive CLI Session</title>
    <content type="html">&lt;p&gt;Again I am a Ruby newb (two days now), but the help is very appreciated in getting to understand the magic behind Ruby and more elegant ways to take care of issues. &lt;/p&gt;

&lt;p&gt;I am looking to allow classes to extend CLI:Session and implement their own commands in a unified manor, below is an example fused into the single class, however ideally the only command for CLI:Session would be 'help' where as the rest would simply extend this class.&lt;/p&gt;

&lt;pre&gt;module CLI
  class Session 
    
    # 
    # Initialize
    #
    def initialize
      @commands = [
          {
            :title =&amp;gt; 'Help',
            :description =&amp;gt; 'Output command help and usage information.',
            :pattern =&amp;gt; /help|usage|commands/,
            :syntax =&amp;gt; 'help | usage | commands',
            :callback =&amp;gt; 'self.usage',
          },
          {
            :title =&amp;gt; 'Source code analysis',
            :description =&amp;gt; 'Quickly reports on the current source code round within this Shard installation.',
            :pattern =&amp;gt; /analyze source/,
            :syntax =&amp;gt; 'analyze source',
            :callback =&amp;gt; 'self.analyze_source',
          }
        ]
    end
      
    #
    # Start the session.
    #
    def start
      loop do
        print &amp;quot;Shard &amp;gt;&amp;gt; &amp;quot;  
        @@args = gets
        @commands.each do |command|                                     
          eval(command[:callback]) if command[:pattern].match @@args    
        end                                                             
      end      
    end
    
    #
    # Output command usage.
    #
    def usage
      @commands.each{|command| puts self.command_usage(command)}
    end
    
    #
    # Get command usage.
    #
    def command_usage(command)
      &amp;lt;&amp;lt;-USAGE
      
        #{command[:title]}
        #{command[:description]}
        Syntax: '#{command[:syntax]}'
USAGE
    end
    
    #
    # Analyze source.
    #
    def analyze_source
      Dir['**/*.rb'].each{ |file| puts `wc -l #{file}` }
    end
  end
end&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/504-interactive-cli-session" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code503</id>
    <published>2008-09-22T15:40:24-07:00</published>
    <updated>2008-10-03T03:55:08-07:00</updated>
    <title>[Ruby] Format Filesize</title>
    <content type="html">&lt;p&gt;Ruby-newb coming through. I only really need to format sizes in bytes, KiB, and MiB, however I suppose a larger scale does not hurt! but im sure this one can be refactored quite alot&lt;/p&gt;

&lt;pre&gt;  #
  # Format filesize.
  #
  def Format.filesize(bytes, label_style = 0)
    size = bytes
    suffix = 'Bytes'
    labels = {
        0 =&amp;gt; ['KB', 'MB'],
        1 =&amp;gt; ['Kilobytes', 'Megabytes'],
        2 =&amp;gt; ['KiB', 'MiB']
      }
    sizes = [1024, 1048576, 1073741824]
    
    # KiB
    if size &amp;gt;= 1024
      size = (size / 1024).round
      suffix = labels[label_style][0]
    end
  
    # MiB
    if size &amp;gt;= 1024
      size = (size / 1024).round
      suffix = labels[label_style][1]
    end
    
    size.to_s + ' ' + suffix
  end&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/503-format-filesize" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code502</id>
    <published>2008-09-22T15:38:30-07:00</published>
    <updated>2008-09-30T15:11:32-07:00</updated>
    <title>[Ruby] Camelize</title>
    <content type="html">&lt;p&gt;I am pretty new to Ruby (one day), however this works fine, but I would like to allow the first character to be lower case optionally, anyone have a smaller solution for this?&lt;/p&gt;

&lt;pre&gt;  
  #
  # Convert a string to CamelCase.
  #
  def camelize
    self.split(/[^a-z0-9]/i).map{|w| w.capitalize}.join
  end&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/502-camelize" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code315</id>
    <published>2008-06-09T20:52:53-07:00</published>
    <updated>2008-06-10T01:44:27-07:00</updated>
    <title>[PHP] Dynamically invoking static classes?</title>
    <content type="html">&lt;p&gt;Hey guys, I should have really thought ahead with this before I went ahead and wrote a good 15 classes but either way my core class needs a mechanism to invoke 'hooks' within each of the other classes available within the scope. Eval() does work, however it obviously outputs an error when the 'hook' does not exist which is certainly no good.. Is there any good clean way this can be done?&lt;/p&gt;

&lt;pre&gt;  static public function invoke($hook) {
    $packages = array();
    $results = array();  
    
    $packages['libraries'] = self::$libraries;
    $packages['modules'] = self::$modules;
    
    foreach((array) $packages AS $type =&amp;gt; $names){
      foreach((array) $names AS $name){
        switch($type){
          case 'libraries':
            $result = @eval(&amp;quot;{$name}::{$hook}();&amp;quot;);
            break;
            
          case 'modules':
            $result = @eval(&amp;quot;{$name}Module::{$hook}();&amp;quot;);
            break;
        }
         
        if (is_array($results)){
          $results = array_merge($results, (array) $result);
        }
      }
    }
    
    return $results;  
  }&lt;/pre&gt;</content>
    <author>
      <name>Tj Holowaychuk</name>
      <email>tj@vision-media.ca</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/315-dynamically-invoking-static-classes" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code265</id>
    <published>2008-03-24T00:00:15-07:00</published>
    <updated>2008-06-11T09:39:22-07:00</updated>
    <title>[PHP] Command-Line TicTacToe</title>
    <content type="html">&lt;p&gt;Just wondering if there are any ways to make this smaller.&lt;/p&gt;

&lt;pre&gt;&amp;lt;?php
$std = fopen(&amp;quot;php://stdin&amp;quot;, &amp;quot;r&amp;quot;);
echo &amp;quot;TICTACTOE\n\n\n\n&amp;quot;;
function letsSeeUm($taken){
  foreach(range(1, 9) as $i) ${&amp;quot;s&amp;quot; . $i} = array_key_exists($i, $taken) ? $taken[$i]:&amp;quot; &amp;quot;;
  echo &amp;quot;   +   +   \n $s1 + $s2 + $s3 \n   +   +   \n+++++++++++\n   +   +   \n $s4 + $s5 + $s6 \n   +   +   \n+++++++++++\n   +   +   \n $s7 + $s8 + $s9 \n   +   +   \n\n&amp;quot;;
}
function check($squ, $em = &amp;quot;x&amp;quot;){
  if(($squ[1] == $em &amp;amp;&amp;amp; $squ[2] == $em &amp;amp;&amp;amp; $squ[3] == $em) || ($squ[4] == $em &amp;amp;&amp;amp; $squ[5] == $em &amp;amp;&amp;amp; $squ[6] == $em) || ($squ[7] == $em &amp;amp;&amp;amp; $squ[8] == $em &amp;amp;&amp;amp; $squ[9] == $em) || ($squ[1] == $em &amp;amp;&amp;amp; $squ[4] == $em &amp;amp;&amp;amp; $squ[7] == $em) || ($squ[2] == $em &amp;amp;&amp;amp; $squ[5] == $em &amp;amp;&amp;amp; $squ[8] == $em) || ($squ[3] == $em &amp;amp;&amp;amp; $squ[6] == $em &amp;amp;&amp;amp; $squ[9] == $em) || ($squ[1] == $em &amp;amp;&amp;amp; $squ[5] == $em &amp;amp;&amp;amp; $squ[9] == $em) || ($squ[3] == $em &amp;amp;&amp;amp; $squ[5] == $em &amp;amp;&amp;amp; $squ[7] == $em)) return true;
  return false;
}
$squares = array();
$player = 1;
while(1){
  echo str_repeat(&amp;quot;\n&amp;quot;, 100);
  letsSeeUm($squares);
  echo &amp;quot;Player $player&amp;gt; &amp;quot;;
  $input = (int) fgets($std);
  if(!array_key_exists($input, $squares) &amp;amp;&amp;amp; in_array($input, range(1, 9))){
    $squares[$input] = ($player == 1) ? &amp;quot;x&amp;quot;:&amp;quot;o&amp;quot;;
    if(check($squares) || check($squares, &amp;quot;o&amp;quot;)){
      echo str_repeat(&amp;quot;\n&amp;quot;, 100);
      letsSeeUm($squares);
      echo &amp;quot;\nPlayer $player Wins!&amp;quot;;
      die;
    }
    if(count($squares) == 9){
      echo str_repeat(&amp;quot;\n&amp;quot;, 100);
      letsSeeUm($squares);    
      echo &amp;quot;\nDraw!&amp;quot;;
      die;
    }
    $player = $player == 1 ? 2:1;
  }
}&lt;/pre&gt;</content>
    <author>
      <name>techietim</name>
      <email>timothy.andrew.cooper@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/265-command-line-tictactoe" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor525</id>
    <published>2007-10-24T02:45:19-07:00</published>
    <title>[Ruby] On Getting QWERTY misstypes</title>
    <content type="html">&lt;p&gt;Hi, I don't how to write a Ruby solution but you can have some idea looking at this Perl module.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://search.cpan.org/~krburton/String-KeyboardDistance-1.01/KeyboardDistance.pm" target="_blank"&gt;http://search.cpan.org/~krburton/String-KeyboardDistance-1.01/KeyboardDistance.pm&lt;/a&gt;&lt;/p&gt;

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

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/100-getting-qwerty-misstypes/refactors/525" rel="alternate"/>
  </entry>
</feed>

