Rails 中常用方法的好地方在哪里?

发布于 2024-08-03 10:11:40 字数 431 浏览 4 评论 0原文

我有一个方法,我已经开始在多个模型中使用该方法进行网页抓取,最好将其保存在哪里?我应该把它放在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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空气里的味道 2024-08-10 10:11:40

您可以创建一个模块。来自 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

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
庆幸我还是我 2024-08-10 10:11:40

将 retryable.rb 放入 lib/

module Retryable
  extend self

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

使用它:

Retryable.retryable { ... }

或包含命名空间:

include Retryable
retryable { ... }

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 { ... }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文