Class: Murlsh::ImgStore
- Inherits:
-
Object
- Object
- Murlsh::ImgStore
- Defined in:
- lib/murlsh/img_store.rb
Overview
Fetch images from urls and store them locally.
Instance Attribute Summary collapse
-
#storage_dir ⇒ Object
readonly
Returns the value of attribute storage_dir.
Instance Method Summary collapse
-
#headers ⇒ Object
Build headers to send with request.
-
#initialize(storage_dir, options = {}) ⇒ ImgStore
constructor
Fetch images from urls and store them locally.
-
#store_img(img) ⇒ Object
Accept a Magick::ImageList and store it locally.
-
#store_img_data(img_data) {|img| ... } ⇒ Object
Accept a blob of image data and store it locally.
-
#store_url(url, &block) ⇒ Object
Fetch an image from a url and store it locally.
Constructor Details
#initialize(storage_dir, options = {}) ⇒ ImgStore
Fetch images from urls and store them locally. Options:
-
:user_agent - user agent to send with http requests
18 19 20 21 |
# File 'lib/murlsh/img_store.rb', line 18 def initialize(storage_dir, ={}) @storage_dir = storage_dir @user_agent = [:user_agent] end |
Instance Attribute Details
#storage_dir ⇒ Object (readonly)
Returns the value of attribute storage_dir.
71 72 73 |
# File 'lib/murlsh/img_store.rb', line 71 def storage_dir @storage_dir end |
Instance Method Details
#headers ⇒ Object
Build headers to send with request.
24 25 26 27 28 |
# File 'lib/murlsh/img_store.rb', line 24 def headers result = {} result['User-Agent'] = @user_agent if @user_agent result end |
#store_img(img) ⇒ Object
Accept a Magick::ImageList and store it locally.
The filename will be the md5sum of the contents plus the correct extension.
58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/murlsh/img_store.rb', line 58 def store_img(img) img.extend(Murlsh::ImageList) unless img.is_a?(Murlsh::ImageList) img_data = img.to_blob md5 = Digest::MD5.hexdigest(img_data) local_file = "#{md5}#{img.preferred_extension}" local_path = File.join(storage_dir, local_file) unless File.exists?(local_path) Murlsh::openlock(local_path, 'w') { |fout| fout.write img_data } end local_file end |
#store_img_data(img_data) {|img| ... } ⇒ Object
Accept a blob of image data and store it locally.
The filename will be the md5sum of the contents plus the correct extension.
If a block is given the Magick::ImageList created will be yielded before storage.
48 49 50 51 52 |
# File 'lib/murlsh/img_store.rb', line 48 def store_img_data(img_data, &block) img = Magick::ImageList.new.from_blob(img_data) yield img if block_given? store_img img end |
#store_url(url, &block) ⇒ Object
Fetch an image from a url and store it locally.
The filename will be the md5sum of the contents plus the correct extension.
If a block is given the Magick::ImageList created will be yielded before storage.
37 38 39 |
# File 'lib/murlsh/img_store.rb', line 37 def store_url(url, &block) open(url, headers) { |fin| store_img_data fin.read, &block } end |