Last active
December 10, 2015 01:48
-
-
Save NuckChorris/4362519 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 | |
| quote = false | |
| escape = false | |
| buffer = '' | |
| key = '' | |
| input.each_char do |char| | |
| # Handle escape sequences roughly | |
| if escape | |
| case char | |
| when 'n' | |
| buffer << "\n" | |
| else | |
| buffer << char | |
| end | |
| escape = false | |
| end | |
| case char | |
| when '"', '\'' | |
| unless quote = !quote | |
| if haskey | |
| self[key.downcase] = buffer | |
| haskey = false | |
| key = '' | |
| buffer = '' | |
| else | |
| raise 'Parse error' | |
| end | |
| end | |
| when ' ' | |
| unless quote | |
| if not key.empty? | |
| self[key.downcase] = buffer | |
| key = '' | |
| else | |
| self[buffer.downcase] = true | |
| end | |
| buffer = '' | |
| end | |
| when '=' | |
| key = buffer | |
| buffer = '' | |
| when '\\' | |
| escape = true | |
| else | |
| buffer << char | |
| end | |
| end | |
| elsif input.is_a? Hash | |
| self.merge! input | |
| 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