Sha256: 6db313c4feaebaf5958fd774cd76edf462343fe19db2de102b660818d292c453

Contents?: true

Size: 1.7 KB

Versions: 3

Compression:

Stored size: 1.7 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)
      value = current_config[key]
      redirect = nil
      if value.is_a? String and ! (IPAddr.new(value) rescue nil)
        redirect = find(value) if not current_config[value]
      end
      if value
        if redirect
          get(redirect)
        else
          value
        end
      end
    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

3 entries across 3 versions & 1 rubygems

Version Path
landrush-0.18.0 lib/landrush/store.rb
landrush-0.17.0 lib/landrush/store.rb
landrush-0.16.0 lib/landrush/store.rb