Permalink
Browse files

Handle file uploads for Rails and Sinatra

  • Loading branch information...
janko-m committed May 5, 2012
1 parent f5dbfd9 commit a27eb36b6eb65ffb3c3672119002d0ede0e3b302
Showing with 37 additions and 7 deletions.
  1. +4 −0 CHANGELOG.md
  2. +33 −7 lib/flickrie/upload_client.rb
View
@@ -1,5 +1,9 @@
# Flickrie changelog
+## Version 0.4.1
+
+- handle file uploads for Rails and Sinatra smarter (see [this wiki](https://github.com/janko-m/flickrie/wiki/Some-tips.md), tip #7)
+
## Version 0.4.0
- covered `flickr.photos.getContactsPhotos`
@@ -39,13 +39,16 @@ def on_complete(env)
class UploadClient < Faraday::Connection
def upload(media, params = {})
media_file = get_file(media, params[:mime_type])
- post "upload", {:photo => media_file}.merge(params)
+ media_title = get_title(media)
+ post "upload", {:photo => media_file,
+ :title => media_title}.merge(params)
end
def replace(media, media_id, params = {})
- media_file = get_file(media)
+ media_file = get_file(media, params[:mime_type])
+ media_title = get_title(media)
post "replace", {:photo => media_file,
- :photo_id => media_id}.merge(params)
+ :photo_id => media_id, :title => media_title}.merge(params)
end
private
@@ -70,11 +73,21 @@ def replace(media, media_id, params = {})
}.freeze
def get_file(object, mime_type = nil)
- if object.is_a?(String)
- Faraday::UploadIO.new(object, mime_type || get_mime_type(object))
- else
- object
+ if object.class.name == "String"
+ # file path
+ file_path = object
+ mime_type ||= get_mime_type(file_path)
+ elsif object.class.name == "ActionDispatch::Http::UploadedFile"
+ # Rails
+ file_path = object.tempfile
+ mime_type ||= object.content_type
+ elsif object.class.name == "Hash"
+ # Sinatra
+ file_path = object[:tempfile].path
+ mime_type ||= object[:type]
end
+
+ Faraday::UploadIO.new(file_path, mime_type)
end
def get_mime_type(file_path)
@@ -84,5 +97,18 @@ def get_mime_type(file_path)
rescue NoMethodError
raise Error, "Don't know mime type for this extension (#{extension})"
end
+
+ def get_title(object)
+ filename =
+ if object.class.name == "String"
+ File.basename(object)
+ elsif object.class.name == "ActionDispatch::Http::UploadedFile"
+ object.original_filename
+ elsif object.class.name == "Hash"
+ object[:filename]
+ end
+
+ filename.match(/\.\w{3,4}$/).pre_match
+ end
end
end

0 comments on commit a27eb36

Please sign in to comment.