Search code examples
ruby-on-railsrubymodelhelper

Where is a good place for a commonly used method... in rails


I have a method that I've started to use in multiple models for Webscraping, where is the best place to keep it? Should I put it in the application_controller, application _helper? I'm not sure where a good place is to put it for multiple models to use it?

  def self.retryable(options = {}, &block)
    opts = { :tries => 1, :on => Exception }.merge(options)

    retry_exception, retries = opts[:on], opts[:tries]

    begin
      return yield
    rescue retry_exception
      retry if (retries -= 1) > 0
    end

    yield
  end

Solution

  • Put retryable.rb in lib/

    module Retryable
      extend self
    
      def retryable(options = {}, &block) # no self required
      ...
      end
    end
    

    Use it:

    Retryable.retryable { ... }
    

    or including namespace:

    include Retryable
    retryable { ... }