Refactor util/data.rb further

This commit is contained in:
Eliott Appleford 2015-09-20 12:23:47 +00:00
parent 62f431b5ae
commit 91a06a1a35

View file

@ -1,21 +1,10 @@
# Core Pathname library used for traversal require 'yaml'
require 'json'
require 'pathname' require 'pathname'
require 'middleman-core/util'
# DbC
require 'middleman-core/contracts' require 'middleman-core/contracts'
# Shared util methods module Middleman::Util::Data
require 'middleman-core/util'
# Parsing YAML data
require 'yaml'
# Parsing JSON data
require 'json'
module Middleman
module Util
module Data
include Contracts include Contracts
module_function module_function
@ -48,8 +37,6 @@ module Middleman
(?<additional_content>.*) (?<additional_content>.*)
/mx =~ content /mx =~ content
return [{}, content] unless frontmatter
case [start, stop] case [start, stop]
when %w[--- ---], %w[--- ...] when %w[--- ---], %w[--- ...]
[parse_yaml(frontmatter, full_path), additional_content] [parse_yaml(frontmatter, full_path), additional_content]
@ -65,7 +52,7 @@ module Middleman
# @return [Array<Hash, String>] # @return [Array<Hash, String>]
Contract String, Pathname, Bool => Hash Contract String, Pathname, Bool => Hash
def parse_yaml(content, full_path) def parse_yaml(content, full_path)
map_value(YAML.load(content)) symbolize_recursive(YAML.load(content))
rescue StandardError, Psych::SyntaxError => error rescue StandardError, Psych::SyntaxError => error
warn "YAML Exception parsing #{full_path}: #{error.message}" warn "YAML Exception parsing #{full_path}: #{error.message}"
{} {}
@ -76,28 +63,20 @@ module Middleman
# @return [Array<Hash, String>] # @return [Array<Hash, String>]
Contract String, Pathname => Hash Contract String, Pathname => Hash
def parse_json(content, full_path) def parse_json(content, full_path)
map_value(JSON.parse(content)) symbolize_recursive(JSON.parse(content))
rescue StandardError => error rescue StandardError => error
warn "JSON Exception parsing #{full_path}: #{error.message}" warn "JSON Exception parsing #{full_path}: #{error.message}"
{} {}
end end
def symbolize_recursive(hash) def symbolize_recursive(value)
{}.tap do |h| case value
hash.each { |key, value| h[key.to_sym] = map_value(value) }
end
end
def map_value(thing)
case thing
when Hash when Hash
symbolize_recursive(thing) value.map { |k, v| [k.to_sym, symbolize_recursive(v)] }.to_h
when Array when Array
thing.map { |v| map_value(v) } value.map { |v| symbolize_recursive(v) }
else else
thing value
end
end
end end
end end
end end