[英]adding class methods to 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?
有什么指针吗?
Well, you can open up ActiveRecord::Base
and throw a method there: 好了,您可以打开
ActiveRecord::Base
并在其中抛出一个方法:
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. 没有测试代码,看看它是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.