Sha256: bbf4d6e8dd35e7a9bd7185d965953ee696a1a05b5742de6b6e67823719d87944

Contents?: true

Size: 1.44 KB

Versions: 1

Compression:

Stored size: 1.44 KB

Contents

module Landrush
  class Store
    def self.hosts
      @hosts ||= new(Landrush.working_dir.join('hosts.json'))
    end

    def self.config
      @config ||= new(Landrush.working_dir.join('config.json'))
    end

    attr_accessor :backing_file

    def initialize(backing_file)
      @backing_file = Pathname(backing_file)
    end

    def set(key, value)
      write(current_config.merge(key => value))
    end

    def each(*args, &block)
      current_config.each(*args, &block)
    end

    def delete(key)
      write(current_config.reject { |k, v| k == key || v == key })
    end

    def has?(key, value = nil)
      if value.nil?
        current_config.has_key? key
      else
        current_config[key] == value
      end
    end

    def find(search)
      search = (IPAddr.new(search).reverse) if (IPAddr.new(search) rescue nil)
      current_config.keys.detect do |key|
        key.casecmp(search) == 0   ||
          search =~ /#{key}$/i     ||
          key    =~ /^#{search}\./i
      end
    end

    def get(key)
      current_config[key]
    end

    def clear!
      write({})
    end

    protected

    def current_config
      if backing_file.exist?
        begin
          JSON.parse(File.read(backing_file))
        rescue JSON::ParserError
          {}
        end
      else
        {}
      end
    end

    def write(config)
      File.open(backing_file, "w") do |f|
        f.write(JSON.pretty_generate(config))
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
landrush-0.19.0 lib/landrush/store.rb