Created
March 1, 2013 16:08
-
-
Save NuckChorris/5065643 to your computer and use it in GitHub Desktop.
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
| class Sold::Clause | |
| def initialize (input) | |
| if input.is_a? String | |
| p input | |
| # State flags and buffers | |
| @quote = false | |
| @escape = false | |
| @buffer = '' | |
| @key = '' | |
| @prev = '' | |
| @section = 0 | |
| # Pieces | |
| @command = [] | |
| @arguments = {} | |
| @input = '' | |
| input.each_char do |char| | |
| self << char | |
| end | |
| flush | |
| elsif input.is_a? Hash | |
| self.merge! input | |
| end | |
| end | |
| def << (char) | |
| if @escape | |
| if char == 'n' | |
| @buffer << "\n" | |
| else | |
| @buffer << char | |
| end | |
| @escape = false | |
| else | |
| # Mode Switchers | |
| # This one checks for -- | |
| if @prev == '-' | |
| if @section == 0 && @char == '-' | |
| @section = 1 | |
| else | |
| @buffer << @prev | |
| end | |
| end | |
| case char | |
| when '"', "'" # Marking the start or end of a quoted string | |
| @quote = !@quote | |
| when ' ' # Separator | |
| if @quote # Except in quoted strings | |
| @buffer << char | |
| else | |
| if @key.empty? | |
| self[@buffer.downcase] = true | |
| else | |
| self[@key.downcase] = @buffer | |
| @key = '' | |
| end | |
| @buffer = '' | |
| end | |
| when '=' # key=value | |
| @key = @buffer | |
| @buffer = '' | |
| when "\\" # Escape sequence | |
| @escape = true | |
| else # Errything else | |
| @buffer << char | |
| end | |
| end | |
| end | |
| def flush | |
| if @key.empty? | |
| self[@buffer.downcase] = true | |
| else | |
| self[@key.downcase] = @buffer | |
| end | |
| end | |
| def to_s | |
| out = [] | |
| self.each do |key, value| | |
| if value == true | |
| out.push key | |
| elsif value.include? ' ' | |
| out.push "" | |
| out.last << key | |
| out.last << '=' | |
| out.last << '"' + value.to_s.gsub('"', '\\"') + '"' | |
| else | |
| out.push key + '=' + value.to_s.gsub('"', '\\\"') | |
| end | |
| end | |
| return out.join ' ' | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment