添加类方法的ActiveRecord :: Base的 [英] adding class methods to ActiveRecord::Base

查看:302
本文介绍了添加类方法的ActiveRecord :: Base的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个实例方法,这也是一个回调(如果是有道理的),做一些东西,那是无关紧要的。我很想能够只是调用:

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?

推荐答案

好了,你可以打开的ActiveRecord :: Base的和投掷的方法有:

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

没有测试code,看看它是否工作。

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

这篇关于添加类方法的ActiveRecord :: Base的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆