简体   繁体   中英

How to share class methods between multiple data models in Rails?

I have multiple Active Record data models in Ruby on Rails that need to share class methods. I could easily declare the methods in all the classes but that is against the DRY principle.

I've looked at declaring a module and using 'include' to mixin the code but that seems to only work with instance methods, not class methods.

What is the preferred way to do this in Ruby/Rails? (I tried to create a base ActiveRecord class and inherit from that, but ActiveRecord freaked out).

The ClassMethods idiom is a common way for a module to supply both class and instance methods: http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/

ActiveRecord shouldn't freak out if you create an abstract base class, as long as you call self.abstract_class = true in that class: http://api.rubyonrails.org/classes/ActiveRecord/Inheritance/ClassMethods.html

Use extend instead of include with a module. That'll mix in class methods instead of instance methods.

Or you absolutely can inherit your base model from ActiveRecord::Base and inherit all your normal models from this base. ActiveRecord shouldn't freak out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM