Class: Imgur2
- Inherits:
-
Struct
- Object
- Struct
- Imgur2
- Defined in:
- lib/imgur2.rb
Overview
Stupid simple class for uploading to imgur.
client = Imgur2.new 'my imgur key'
p File.open(ARGV[0], 'rb') { |f|
client.upload f
}
Constant Summary collapse
- VERSION =
'1.2.1'
Instance Attribute Summary collapse
-
#key ⇒ Object
Returns the value of attribute key.
Class Method Summary collapse
Instance Method Summary collapse
- #follow_redirect(url) ⇒ Object
-
#paste(link) ⇒ Object
Tries to find clipboard copy executable and if found puts
link
in your clipboard. - #upload(io) ⇒ Object
Instance Attribute Details
#key ⇒ Object
Returns the value of attribute key
11 12 13 |
# File 'lib/imgur2.rb', line 11 def key @key end |
Class Method Details
.get_image(filename = nil) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/imgur2.rb', line 32 def self.get_image filename = nil return open(filename, 'rb') if filename begin require 'pasteboard' require 'stringio' clipboard = Pasteboard.new data = clipboard[0, Pasteboard::Type::JPEG] return StringIO.new data if data rescue LoadError end $stdin end |
.run(argv) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/imgur2.rb', line 14 def self.run argv client = Imgur2.new '65aea9a07b4f6110c90248ffa247d41a' fh = get_image argv[0] response = client.upload(fh) if response.key? 'error' $stderr.puts response['error']['message'] exit 1 end link = response['upload']['links']['original'] link = client.follow_redirect link client.paste link puts link ensure fh.close if fh end |
Instance Method Details
#follow_redirect(url) ⇒ Object
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/imgur2.rb', line 61 def follow_redirect url follower = lambda do |uri, depth| raise "too many redirects" if depth > 3 parsed = URI.parse uri resp = Net::HTTP.start(parsed.host) { |http| head = Net::HTTP::Head.new parsed.path http.request head } if Net::HTTPRedirection === resp follower.call resp['Location'], depth + 1 else uri end end follower.call url, 0 end |
#paste(link) ⇒ Object
Tries to find clipboard copy executable and if found puts link
in your clipboard.
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/imgur2.rb', line 85 def paste link require 'pasteboard' clipboard = Pasteboard.new clipboard.put_url link rescue LoadError clipboard = %w{ /usr/bin/pbcopy /usr/bin/xclip }.find { |path| File.exist? path } if clipboard IO.popen clipboard, 'w' do |io| io.write link end end end |
#upload(io) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/imgur2.rb', line 49 def upload io url = URI.parse 'http://api.imgur.com/2/upload.json' JSON.parse Net::HTTP.start(url.host) { |http| post = Net::HTTP::Post.new url.path post.set_form_data('key' => key, 'image' => [io.read].pack('m'), 'type' => 'base64') http.request(post).body } end |