Class: Ip2Geo::Methods::Init

Inherits:
Object
  • Object
show all
Defined in:
lib/ip2geo/methods/init.rb

Class Method Summary collapse

Class Method Details

.call(key, options = {}) ⇒ Boolean

Initializes the SDK with the given API key.

Parameters:

  • key (String)

    The API key used to authenticate with Ip2Geo

  • options (Hash) (defaults to: {})

    Optional configuration

Options Hash (options):

  • :version_update_message (Boolean)

    Whether to display version update messages (default: true)

  • :cache (Boolean)

    Whether to enable caching for successful conversions (default: true)

  • :cache_max_size (Integer)

    Maximum cached entries, min: 10, max: 50000 (default: 1000)

  • :cache_ttl (Integer)

    Cache TTL in seconds, min: 30, max: 86400 (default: 300)

Returns:

  • (Boolean)

    Whether the initialization was successful



16
17
18
19
20
21
22
23
24
25
26
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/ip2geo/methods/init.rb', line 16

def call(key, options = {})
  Data::State.auth_key = key
  Data::State.version_update_message = options.fetch(:version_update_message, true)

  if options.key?(:cache)
    unless options[:cache] == true || options[:cache] == false
      raise ArgumentError, 'Init: "cache" must be a boolean.'
    end

    Data::State.cache = options[:cache]
  end

  if options.key?(:cache_max_size)
    unless options[:cache_max_size].is_a?(Integer)
      raise ArgumentError, 'Init: "cache_max_size" must be an integer.'
    end

    if options[:cache_max_size] < 10
      raise ArgumentError, 'Init: "cache_max_size" must be at least 10.'
    end

    if options[:cache_max_size] > 50_000
      raise ArgumentError, 'Init: "cache_max_size" must be at most 50000.'
    end

    Data::State.cache_max_size = options[:cache_max_size]
  end

  if options.key?(:cache_ttl)
    unless options[:cache_ttl].is_a?(Integer)
      raise ArgumentError, 'Init: "cache_ttl" must be an integer (seconds).'
    end

    if options[:cache_ttl] < 30
      raise ArgumentError, 'Init: "cache_ttl" must be at least 30 (30 seconds).'
    end

    if options[:cache_ttl] > 86_400
      raise ArgumentError, 'Init: "cache_ttl" must be at most 86400 (1 day).'
    end

    Data::State.cache_ttl = options[:cache_ttl]
  end

  Helpers::Cache.clear unless Data::State.cache
  Helpers::CheckVersion.call

  true
rescue StandardError => e
  Data::State.reset!
  warn "[Ip2Geo::Init] Error: #{e.message}"
  false
end