Sha256: 3eda0ca52741f3aac0e25435be10a5f7f7dbabac7b5abf3c4f4242a461e69e9b

Contents?: true

Size: 1.56 KB

Versions: 1

Compression:

Stored size: 1.56 KB

Contents

require "social_avatar_proxy/remote_file_resolver"
require "social_avatar_proxy/avatar_file"

module SocialAvatarProxy
  class Avatar
    attr_reader :identifier

    def initialize(identifier)
      @identifier = identifier
    end
    
    # downloads the avatar from the remote server
    def body
      response.body
    end
    
    # returns whether the avatar returns a successful response
    def exist?
      @exists ||= begin
        # ensure the response is success/redirect
        response.code.to_i.between?(200, 399)
      end
    end
    alias_method :exists?, :exist?
    
    # returns the last modified timestamp
    def last_modified
      @last_modified ||= begin
        response["last-modified"] &&
        Time.parse(response["last-modified"]) or
        Time.now
      end
    end
    
    # returns the content type of the file
    def content_type
      @content_type ||= begin
        response["content-type"] ||
        "image/jpeg"
      end
    end
    
    # in the base Avatar class, we'll use the identifier as the URL
    def remote_url
      identifier
    end
    
    # return a temporary file object
    def file
      AvatarFile.new(File.basename(remote_url)).tap do |file|
        begin
          file.write(body)
          file.content_type(content_type)
          file.mtime(last_modified)
          file.rewind
        rescue
          file.close
          raise
        end
      end if exist?
    end
    
    private    
    # request the remote file
    def response
      @response ||= RemoteFileResolver.new(remote_url).resolve
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
social-avatar-proxy-2.0.0 lib/social_avatar_proxy/avatar.rb