简体   繁体   中英

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

You could create a module. An example from the Altered Beast project: (I often look in other projects how they solve specific problems)

# app/models/user/editable.rb
module User::Editable
  def editable_by?(user, is_moderator = nil)
    is_moderator = user.moderator_of?(forum) if is_moderator.nil?
    user && (user.id == user_id || is_moderator)
  end
end

And in the models:

# app/models/post.rb
class Post < ActiveRecord::Base
  include User::Editable
  # ...
end

# app/models/topic.rb
class Topic < ActiveRecord::Base
  include User::Editable
  # ...
end

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 { ... }

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