Class: Gorynich::Fetcher

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fetcher: nil, namespace: nil, cache_expiration: nil) ⇒ Fetcher

Create instance of fetcher

Parameters:

  • fetcher (Object) (defaults to: nil)

    data source

  • namespace (String, Symbol) (defaults to: nil)

    cache namespace

  • cache_expiration (Integer) (defaults to: nil)

    how long your cache will be alive



16
17
18
19
20
# File 'lib/gorynich/fetcher.rb', line 16

def initialize(fetcher: nil, namespace: nil, cache_expiration: nil)
  @fetcher = fetcher || Gorynich.configuration.fetcher
  @namespace = namespace || Gorynich.configuration.namespace
  @cache_expiration = cache_expiration || Gorynich.configuration.cache_expiration
end

Instance Attribute Details

#cache_expirationObject (readonly)

Returns the value of attribute cache_expiration.



7
8
9
# File 'lib/gorynich/fetcher.rb', line 7

def cache_expiration
  @cache_expiration
end

#fetcherObject (readonly)

Returns the value of attribute fetcher.



7
8
9
# File 'lib/gorynich/fetcher.rb', line 7

def fetcher
  @fetcher
end

#namespaceObject (readonly)

Returns the value of attribute namespace.



7
8
9
# File 'lib/gorynich/fetcher.rb', line 7

def namespace
  @namespace
end

Instance Method Details

#fetchHash

Load data from source

Returns:

  • (Hash)

Raises:



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/gorynich/fetcher.rb', line 27

def fetch
  cfg = Gorynich.configuration.cache.fetch(
    cache_key, expires_in: @cache_expiration.seconds, namespace: @namespace
  ) do
    if @fetcher.nil?
      {}
    elsif @fetcher.is_a?(Array)
      result = {}
      @fetcher.each do |f|
        result =
          begin
            f.fetch
          rescue ::StandardError
            {}
          end
        break unless result.empty?
      end
      result
    else
      @fetcher.fetch
    end
  end

  raise Error, 'Config is empty' if cfg.empty?

  cfg.deep_transform_keys(&:downcase)
end

#resetObject

Delete cache



58
59
60
# File 'lib/gorynich/fetcher.rb', line 58

def reset
  Gorynich.configuration.cache.delete(cache_key)
end