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

前端 未结 2 1387
清歌不尽
清歌不尽 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:38

    The simplest solution would be to create a module under lib and mix this into the models that need it, for instance, in lib/fooable.rb:

    module Fooable
      def do_foo
      end
    end
    

    And then in your various models:

    class MyModel < ActiveRecord::Base
      include Fooable
    end
    

    No need to require fooable.rb, the Rails autoloading mechanism will find it for you as long as it's named using correct conventions.

提交回复
热议问题