1

我有一个方法,我已经开始在多个模型中使用 Webscraping,保存它的最佳位置在哪里?我应该把它放在application_controller,application_helper中吗?我不确定将它放在哪个好地方供多个模型使用它?

  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
4

2 回答 2

3

您可以创建一个模块。来自Altered Beast项目的一个例子:(我经常在其他项目中查看它们如何解决特定问题)

# 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

在模型中:

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

# app/models/topic.rb
class Topic < ActiveRecord::Base
  include User::Editable
  # ...
end
于 2009-09-02T10:58:43.280 回答
1

将 retryable.rb 放入 lib/

module Retryable
  extend self

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

用它:

Retryable.retryable { ... }

或包括命名空间:

include Retryable
retryable { ... }
于 2009-09-07T11:35:28.393 回答