Created
February 13, 2013 04:08
-
-
Save NuckChorris/4942188 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 Arguments < Hash | |
| def initialize (input) | |
| if input.is_a? String | |
| p input | |
| @quote = false | |
| @escape = false | |
| @buffer = '' | |
| @key = '' | |
| 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 | |
| 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