Skip to content

Instantly share code, notes, and snippets.

@cyx
Created January 30, 2010 00:02
Show Gist options
  • Save cyx/290281 to your computer and use it in GitHub Desktop.
Save cyx/290281 to your computer and use it in GitHub Desktop.
require 'open-uri'
require 'tempfile'
class Downloadable
# The filename, *not* including the path, of the "uploaded" file
attr_reader :original_filename
# The content type of the "uploaded" file
attr_accessor :content_type
def initialize(uri, content_type = Mime::TEXT, binary = false)
@stream = open(uri)
@content_type = content_type
@original_filename = File.basename( uri )
@tempfile = Tempfile.new(@original_filename)
@tempfile.set_encoding(Encoding::BINARY) if @tempfile.respond_to?(:set_encoding)
@tempfile.binmode if binary
File.open(@tempfile.path, 'wb') { |f| f.write @stream.read }
end
def path #:nodoc:
@tempfile.path
end
alias local_path path
def method_missing(method_name, *args, &block) #:nodoc:
@tempfile.__send__(method_name, *args, &block)
end
end
__END__
== How to use ==
d = Downloadable.new('http://www.google.com.ph/intl/en_com/images/logo_plain.png', 'image/png')
Photo.create! :image => d, :attachable => e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment