Sha256: 542150ff053ab6b82272c98c8ae659449e378f4ed2d8fa5989843260f6d6feb5

Contents?: true

Size: 1.19 KB

Versions: 2

Compression:

Stored size: 1.19 KB

Contents

class Muchkeys::ConsulClient
  delegate :config, to: :application
  class SafetyViolation < StandardError; end

  attr_accessor :application

  def initialize(application)
    @application = application
  end

  def unsafe=(toggle)
    @unsafe = toggle
  end

  def get(key, recursive: false)
    url = recursive ? consul_recurse_url(key) : consul_key_url(key)
    response = Net::HTTP.get_response(url)

    if response.code == "200"
      response.body
    else
      nil
    end
  rescue Errno::ECONNREFUSED
    nil
  end

  def put(value, key, **options)
    url = consul_insert_key_url(key, **options)
    raise SafetyViolation unless @unsafe
    Net::HTTP.new(url.host, url.port).send_request('PUT', url.request_uri, value)
  end

  def delete(key)
    url = consul_key_url(key)
    raise SafetyViolation unless @unsafe
    Net::HTTP.new(url.host, url.port).send_request('DELETE', url.request_uri)
  end

  def consul_key_url(key_name)
    URI("#{config.consul_url}/v1/kv/#{key_name}?raw")
  end

  def consul_recurse_url(path)
    URI("#{config.consul_url}/v1/kv/#{path}?recurse")
  end

  def consul_insert_key_url(key_name, **query)
    URI("#{config.consul_url}/v1/kv/#{key_name}?#{query.to_query}")
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
muchkeys-0.7.1 lib/muchkeys/consul_client.rb
muchkeys-0.7.0 lib/muchkeys/consul_client.rb