Posts tagged ‘Ruby’

I have a singleton method in one of my service calls which I wanted to have memoize functionality. While there are several ways to do, I wanted to have a simple elegant way to do it. I have seen an example from Dave Thomas for instance methods. This one is similar to one of his examples but works for singleton methods. Comments are welcome. :)

module CacheHelper
  def cache(name)
    eigen_class = class << self
      self
    end
    eigen_class.instance_eval do
      memory = {}
      original = "original#{name}"
      alias_method(original, name)
      define_method(name) do |*args|
        if memory.has_key?(args)
          memory[args]
        else
          memory[args] = send original, *args
        end
      end
    end
  end
end

I am working on rails application that talks to legacy oracle database. The id columns are named as oid and they are of number type. The emulate_integers_by_column_name attribute in oracle enhanced driver allows us to set this attribute to true, to change the type of id columns to fixnum. I wrote this code to override and work for columns with oid in its name. All you need to do is put it in a separate file in initializers directory and off you go it works.. :)

ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.emulate_integers_by_column_name = true

ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.instance_eval do
  def is_integer_column?(name)
      name =~ /(^|_)oid$/i
  end
end

I could not find a good example of using ruby hessian api. Here is a sample code that I wrote at my work place.
Hope this helps.

require 'hessian'
class Person

@@client = Hessian::HessianClient.new('url')

class << self

    def find arg

      new(@@client.method(arg))

    end

  end

def initialize(hash)

    hash.each do |k,v|

      self.instance_variable_set("@#{k}", v)

      self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")})

      self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)})

    end

  end

end

p = Person.find('obama')