0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.