How do I make a method available to both my controller and model in Rails?

前端 未结 3 1997
面向向阳花
面向向阳花 2021-02-08 09:54

I have a private method in my Rails app to connect to Amazon S3, execute a passed block of code, then close the connection to S3. It looks like so;

def S3
  AWS:         


        
3条回答
  •  别那么骄傲
    2021-02-08 10:19

    Your hunch is correct: you can put a module in the lib directory. In order to make these methods available to your models, simply include it with:

    class Model < ActiveRecord::Base
      include MyModule
    end
    

    The included module's instance methods will become instance methods on your class. (This is known as a mixin)

    module MyModule
      def S3
        #...
      end
    end
    

提交回复
热议问题