Where to put model “utility” functions in Ruby on Rails

前端 未结 2 1388
清歌不尽
清歌不尽 2020-12-25 11:36

I have a rails app with several models.

I have a function that I want to access from several models.

What\'s the best place to put this code and how can I ma

2条回答
  •  失恋的感觉
    2020-12-25 12:34

    In order to lessen the repetition of code, you could also create a main class which would include that module and the simply inherit from it from every model you'd like to share the behaviour.

    Something like:

    module Fooable
      def do_foo
      end
    end
    
    class ParentModel < ActiveRecord::Base
      include Fooable
    end
    
    class Product < ParentModel end
    class User < ParentModel end
    class Item < ActiveRecord::Base end
    

    Thus, in that example, both Product and User would share the do_foo functionality and Item would not.

提交回复
热议问题