Sha256: a2c8d26a82f3684d876f38213a34a07e3a546d16b4c673090b8730dbd6e9277d

Contents?: true

Size: 1.02 KB

Versions: 6

Compression:

Stored size: 1.02 KB

Contents

module PinchHitter::Message
  module Json
    def json_message(file, overrides={})
      json_file = load_json_file file
      replace_json json_file, overrides
    end

    def valid_json?(json)
      begin
        JSON.parse json
        return true
      rescue
        return false
      end
    end

  private
    def load_json_file(filename)
      IO.read filename
    end

    def replace_json(content, overrides={})
      return content if overrides.empty?
      doc = JSON.parse(content)
      overrides.each do |key, value|
        hash = find_nested_hash(doc, key)
        if has_key(hash, key)
          hash[key] = value
        end
      end
      doc.to_s
    end

    def find_nested_hash(parent, key)
      return parent if has_key(parent, key)
      return nil unless parent.respond_to? :each

      found = nil
      parent.find do |parent_key, child|
        found = find_nested_hash(child, key)
      end
      found
    end

    def has_key(hash, key)
      hash.respond_to?(:key?) && hash.key?(key)
    end

  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
pinch_hitter-0.5.3 lib/pinch_hitter/message/json.rb
pinch_hitter-0.5.2 lib/pinch_hitter/message/json.rb
pinch_hitter-0.5.1 lib/pinch_hitter/message/json.rb
pinch_hitter-0.5 lib/pinch_hitter/message/json.rb
pinch_hitter-0.4 lib/pinch_hitter/message/json.rb
pinch_hitter-0.3 lib/pinch_hitter/message/json.rb