簡體   English   中英

rails中的一個常用方法好在哪里...

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

我有一種方法已開始在多個模型中用於 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

您可以創建一個模塊。 來自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

將 retryable.rb 放在 lib/

module Retryable
  extend self

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

用它:

Retryable.retryable { ... }

或包括命名空間:

include Retryable
retryable { ... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM