Class: GsImgFetcher::Fetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/gs_img_fetcher/fetcher.rb

Constant Summary collapse

INITIALIZED =
:initialized
FETCHED =
:fetched
FETCH_FAILED =
:fetch_failed
SAVED =
:saved
SAVE_FAILED =
:save_failed

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(entry, output_dir, max_size: nil) ⇒ Fetcher

Returns a new instance of Fetcher.



16
17
18
19
20
21
22
# File 'lib/gs_img_fetcher/fetcher.rb', line 16

def initialize(entry, output_dir, max_size: nil)
  @entry = entry
  @output_dir = output_dir
  @max_size = max_size.yield_self { |s| s.present? ? s * 1024 * 1024 : nil }
  @uuid = SecureRandom.uuid
  @state = INITIALIZED
end

Instance Attribute Details

#stateObject (readonly)

Returns the value of attribute state.



14
15
16
# File 'lib/gs_img_fetcher/fetcher.rb', line 14

def state
  @state
end

#uuidObject (readonly)

Returns the value of attribute uuid.



14
15
16
# File 'lib/gs_img_fetcher/fetcher.rb', line 14

def uuid
  @uuid
end

Instance Method Details

#failed?Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/gs_img_fetcher/fetcher.rb', line 49

def failed?
  [FETCH_FAILED, SAVE_FAILED].include?(state)
end

#fetchObject



24
25
26
27
28
29
30
31
# File 'lib/gs_img_fetcher/fetcher.rb', line 24

def fetch
  @tempfile = Down.download(@entry.url, **{ max_size: @max_size }.compact)
  @state = FETCHED
  log_fetched
rescue Down::Error => e
  @state = FETCH_FAILED
  log_error(e)
end

#fetched?Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/gs_img_fetcher/fetcher.rb', line 53

def fetched?
  FETCHED == state
end

#output_pathObject



45
46
47
# File 'lib/gs_img_fetcher/fetcher.rb', line 45

def output_path
  @output_path ||= File.join(@output_dir, [uuid, @entry.extension].join('.'))
end

#saveObject



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/gs_img_fetcher/fetcher.rb', line 33

def save
  return unless fetched?

  FileUtils.mkdir_p(@output_dir)
  FileUtils.mv(tempfile.path, output_path)
  @state = SAVED
  log_saved
rescue StandardError => e
  @state = SAVE_FAILED
  log_error(e)
end

#successful?Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/gs_img_fetcher/fetcher.rb', line 57

def successful?
  SAVED == state
end