views:

50

answers:

1

I have created an instance method which is also a callback (if that makes sense) which does some stuff thats irrelevant. I would love to be able to just call:

class Model < ActiveRecord::Base
  fix_camelcase_columns  
end

Instead at the moment I have this:

def after_find
  self.class.columns.each do |column|
    self.instance_eval("def #{column.name.to_underscore}; self.#{column.name}; end;")
  end
end

I would love to abstract this and use it on other classes. Any pointers?

+2  A: 

Well, you can open up ActiveRecord::Base and throw a method there:

class ActiveRecord::Base
  def self.fix_camelcase_columns
    define_method :after_find do 
      ...
    end
  end
end

For a cleaner way, create a module:

module CamelcaseFixer
  def self.included(base)
    base.extend(self)
  end

  def fix_camelcase_columns
    define_method :after_find do
      ...
    end     
  end
end

and then in your model do

class Model < ActiveRecord::Base
  include CamelcaseFixer
  fix_camelcase_columns  
end

Didn't test the code, see if it works.

neutrino
beuatiful! thank you! I was close on the monkey patching, but this is better!
stuartc
great solution and explanation.
Brian T Hannan