简体   繁体   English

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

[英]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?我有一种方法已开始在多个模型中用于 Webscraping,保存它的最佳位置在哪里? Should I put it in the application_controller, application _helper?我应该把它放在 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)来自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

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/将 retryable.rb 放在 lib/

module Retryable
  extend self

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

Use it:用它:

Retryable.retryable { ... }

or including namespace:或包括命名空间:

include Retryable
retryable { ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM