views:

109

answers:

2

I have a method that I've started to use in multiple models for Webscrapping, 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
+3  A: 

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
benvds
Any particular reason you put it in models/user rather than lib?
Mike Woodhouse
i'm not sure how that works... they're not referencing editable_by? in the other models themselves. I tried placing mine in a similar folder #app/models/scrapers/retryable.rb, module Scrapers::Retryable and then referencing it as "include Scrapers::Retryable" but it gives me "undefined method `retryable' for Get_Data:Class"
holden
+1  A: 

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 { ... }
splattael