[英]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.