Making Static Methods a First Class Citizen

Static methods are the syntactic vinegar of Ruby, they need some extra Syntax to declare and are cumbersome to call. Yet they are the best one can do to get reusable and testable components. Magic to the rescue!

class SomeKindOfClass
  def normal
    self.class.static_normal
  end

  def self.static_normal
  end
end

#self.class.static_normal is not very nice...
#but we could do klass.static_method or static.static_method with:
class Object
  def klass
    self.class
  end
end

#Or go extreme and allow class methods to be called like instance methods
#SomeKindOfClass.new.static_normal
class Object
  def method_missing name, *args
    return self.class.send(name, *args) if self.class.respond_to? name
    super
  end
end

Getting the Caller Method in Ruby

Need to know which method called you ? Its as simple as:
caller = CallChain.caller_method

Alternatively it could be added to Object, but that would be dirty 😉

class CallChain
  def self.caller_method(depth=1)
    parse_caller(caller(depth+1).first).last
  end

  private

  #Stolen from ActionMailer, where this was used but was not made reusable
  def self.parse_caller(at)
    if /^(.+?):(\d+)(?::in `(.*)')?/ =~ at
      file   = Regexp.last_match[1]
      line   = Regexp.last_match[2].to_i
      method = Regexp.last_match[3]
      [file, line, method]
    end
  end
end

ActionView Standalone

require 'action_view'
require 'action_controller/mime' # for Rails 2

render :file=>'foo.html.erb', :locals=>{:user=>User.first}
render :file=>'lib/data_feed.xml.builder', :type=>:rxml, :locals=>{:user=>User.first)

def render(options)
  klass = Class.new(ActionView::Base)
  klass.class_eval{ def url_for(x);x;end } # to be able to use link_to
  klass.new.render(options)
end

Quick Markdown Preview For Github Readme

I write my Readme in marddown, and often it gets messed up and then I have to commit & push until its finally right, so I wrote a small script to get a preview (using githubs markdown library)!

Usage

markdown README.markdown
... chrome pops up with the html preview

Install
gem install redcarpet

Put this into e.g. ~/bin/markdown and do a chmod +x on it

#!/usr/bin/env ruby
raise "gime a file!!" unless ARGV[0]
exec "redcarpet #{ARGV[0]} > /tmp/markdown.html && chromium-browser /tmp/markdown.html"

Alternatively: Interactive Live Preview<

Array.to_ordered_hash replacement for Rails 2.3 ActiveSupport::OrderedHash.new

The simple

ActiveSupport::OrderedHash.new [[1,2]]

does no longer work in Rails 2.3, so I built a small patch for array that make OrderedHash creation simple again.

Code

class Array
  def to_ordered_hash
    ActiveSupport::OrderedHash[self]
  end
end

Usage

hash = [[:key, 'value'], [:key2, :value2], [1, 2]].to_ordered_hash
hash == {:key=>'value', :key2=>:value2, :1=>2}

a more complete but longer/harder version