Skip to content

Instantly share code, notes, and snippets.

@jm
Last active December 14, 2015 03:39
Show Gist options
  • Save jm/5022483 to your computer and use it in GitHub Desktop.
Save jm/5022483 to your computer and use it in GitHub Desktop.
TOML. Because lol.
#######################
#
# 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