1
0
Fork 0
mirror of https://github.com/fog/fog.git synced 2022-11-09 13:51:43 -05:00
fog--fog/lib/fog/core/model.rb
Pieter van de Bruggen 331d58dabf Make Model#reload more resilient against errors.
Connection errors had the behavior of failing catastrophically, which had
some rather unpleasant implications for things like Model#wait_for, which
implicitly reload repeatedly without any protection.

This change may be better suited to special cases (e.g. Model#wait_for).
2011-04-14 15:41:47 -07:00

62 lines
1.5 KiB
Ruby

module Fog
class Model
extend Fog::Attributes::ClassMethods
include Fog::Attributes::InstanceMethods
attr_accessor :collection, :connection
def initialize(new_attributes = {})
merge_attributes(new_attributes)
end
def inspect
Thread.current[:formatador] ||= Formatador.new
data = "#{Thread.current[:formatador].indentation}<#{self.class.name}"
Thread.current[:formatador].indent do
unless self.class.attributes.empty?
data << "\n#{Thread.current[:formatador].indentation}"
data << self.class.attributes.map {|attribute| "#{attribute}=#{send(attribute).inspect}"}.join(",\n#{Thread.current[:formatador].indentation}")
end
end
data << "\n#{Thread.current[:formatador].indentation}>"
data
end
def reload
requires :identity
return unless data = begin
collection.get(identity)
rescue Excon::Errors::SocketError
nil
end
new_attributes = data.attributes
merge_attributes(new_attributes)
self
end
def to_json
require 'json'
attributes.to_json
end
def wait_for(timeout=600, interval=1, &block)
reload
retries = 3
Fog.wait_for(timeout, interval) do
if reload
retries = 3
elsif retries > 0
retries -= 1
sleep(1)
elsif retries == 0
raise Fog::Errors::Error.new("Reload failed, #{self.class} #{self.identity} went away.")
end
instance_eval(&block)
end
end
end
end