Recently, I was working on one ruby on rails project. where base site has many sub sites based on regions. we required to restrict many queries based on current-region/specific-region. the best solution I figured is add functionality to find method instead of using SQL JOINS.
  def self.find(*args)
    if args.first == :first || args.first == :all
      if args.last.is_a?(Hash) && (region = args.last[:for_region]) && region.is_a?(Region)
        with_scope(:find => {:include => [:regionals], 
                                        :conditions =>  "regionals.region_id = #{region.id}"}) do
          args.last.delete(:for_region)
          super(*args)
        end
      else
        super
      end
    else
      super
    end
  end
I wrote above code in Business model. now I'm able to
Business.find(:first, :for_region => current_region)
Business.find(:all, :for_region => current_region)
Business.find(:all, :for_region => Region.find(params[:region_id]), Any other valid find option ...)
isn't it cool?

This is about method_missing featured of ruby, which I had used recently in SimpleTicket well, its Ver2.0 of SimpleTicket, at Architel soon to be used in-house first.afterwards will be released as open-source project.

it creates methods like,

  • `status_to_open`
  • `status_to_contacted`
  • `status_to_pending`
  • `status_to_closed`

changes status of ticket as their name suggests


def method_missing(method_id, *arguments)
  if mdata = /status_to_(open|closed|contacted|pending)/.match(method_id.to_s)
    status = mdata.captures.first
    change_status(Status.find_by_name(status.capitalize).id)
  else
    super
  end
end

I’m loving Ruby