Last active
December 14, 2015 03:39
-
-
Save jm/5022483 to your computer and use it in GitHub Desktop.
TOML. Because lol.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
####################### | |
# | |
# THIS IS NOW A REAL GEM (and much improved...): | |
# https://github.com/jm/toml | |
# | |
####################### | |
require 'time' | |
module TOML | |
class Parser | |
def parse(markup) | |
lines = markup.split("\n").reject {|l| l.start_with?("#") } | |
@parsed = {} | |
@current_key_group = "" | |
lines.each do |line| | |
if line.gsub(/\s/, '').empty? | |
close_key_group | |
elsif line =~ /^\s?\[(.*)\]/ | |
new_key_group($1) | |
elsif line =~ /\s?(.*)=(.*)/ | |
add_key($1, $2) | |
else | |
raise "lmao i have no clue what you're doing: #{line}" | |
end | |
end | |
@parsed | |
end | |
def new_key_group(key_name) | |
@current_key_group = key_name | |
end | |
def add_key(key, value) | |
@parsed[@current_key_group] ||= {} | |
@parsed[@current_key_group][key.strip] = coerce(strip_comments(value)) | |
end | |
def strip_comments(text) | |
text.split("#").first | |
end | |
def coerce(value) | |
value = value.strip | |
if value =~ /\[(.*)\]/ | |
# array | |
array = $1.split(",").map {|s| s.strip.gsub(/\"(.*)\"/, '\1')} | |
return array | |
elsif value =~ /\"(.*)\"/ | |
# string | |
return $1 | |
end | |
begin | |
time = Time.parse(value) | |
return time | |
rescue | |
end | |
begin | |
int = Integer(value) | |
return int | |
rescue | |
end | |
raise "lol no clue what [#{value}] is" | |
end | |
def close_key_group | |
@current_key_group = "" | |
end | |
end | |
end | |
testing = <<-MARKUP | |
# This is a TOML document. Boom. | |
title = "TOML Example" | |
[owner] | |
name = "Tom Preston-Werner" | |
organization = "GitHub" | |
bio = "GitHub Cofounder & CEO\\nLikes tater tots and beer." | |
dob = 1979-05-27T07:32:00Z # First class dates? Why not? | |
[database] | |
server = "192.168.1.1" | |
ports = [ "8001", "8001", "8002" ] | |
connection_max = 5000 | |
MARKUP | |
require 'pp' | |
pp TOML::Parser.new.parse(testing) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment