adding class methods to ActiveRecord::Base

人走茶凉 提交于 2019-12-25 03:22:42

问题


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:


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.



来源:https://stackoverflow.com/questions/2921215/adding-class-methods-to-activerecordbase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!