Archive

Posts Tagged ‘ruby’

a tiny ruby retry class

December 31, 2011 Leave a comment

Here’s a tiny ruby retry class.

class Retryable
  def self.attempt(options = {}, &block)
    opts = { :tries => 1, :on => Exception }.merge(options)
    retry_exception, tries = opts[:on], opts[:tries]
    begin
      return yield
    rescue retry_exception
      retry if (tries -= 1) > 0
      raise
    end
    yield
  end
end

Usage is like this

Retryable.attempt do
     #something that might fail, but you want to try it a few times
end
Categories: tech Tags:

journey from .Net to Ruby

November 19, 2011 Leave a comment

about a year ago, i switched from the .Net stack to Ruby/Rails.  I dont feel religious toward either stack, i think of them both as a tool in my quiver.  i get many questions from .Netters looking to do the same thing, looking for tips.  So, here goes:

  • get your black belt in ruby first.  learn to write idiomatic ruby!
  • go thru the Rails3 tutorial http://ruby.railstutorial.org/
  • pick a good editor (RubyMine is an excellent choice!)

After I got thru these steps, i started to specialize knowedge thru the Railscasts and Peepcode screencasts.  And build stuff in your spare time using these tools!

Categories: tech Tags: ,

memoize in Ruby

November 19, 2011 Leave a comment

Going thru this exercise really helped me gain some depth in ruby programming.  Take advantage of the metaprogramming & singleton classes.

#adapted from Dave Thomas's screencast on metaprogramming in Ruby

module Memoize
  def remember(name, &block)
 
    define_method(name, &block)
 
    orig = instance_method(name)
 
    mem = {}
    define_method(name) do |*args|
      if mem.has_key?(args)
        mem[args]
      else
        bound = orig.bind(self)
        mem[args] = bound.call(*args)
      end
    end
  end
end
 
class Finder
   extend Memoize
 
  remember :find do |*objs|
    expensive(*objs)
  end
 
  def expensive(*objs)
    puts "expensive"
    objs.inject{|m,n| m + n }
  end
end

 
#test it
d = Finder.new
puts d.find(1,2,3)
puts d.find(1,2,3) #expensive is not called here
Categories: tech Tags: ,
%d bloggers like this: