Class: Murlsh::ImgStore

Inherits:
Object
  • Object
show all
Defined in:
lib/murlsh/img_store.rb

Overview

Fetch images from urls and store them locally.

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (ImgStore) initialize(storage_dir, options = {})

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, options={})
  @storage_dir = storage_dir
  @user_agent = options[:user_agent]
end

Instance Attribute Details

- (Object) storage_dir (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

- (Object) headers

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

- (Object) store_img(img)

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

- (Object) store_img_data(img_data) {|img| ... }

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.

Yields:

  • (img)


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

- (Object) store_url(url, &block)

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