Class: TOML::Generator
- Inherits:
-
Object
- Object
- TOML::Generator
- Defined in:
- lib/toml/generator.rb
Constant Summary collapse
- @@injected =
Whether or not the injections have already been done.
false
Instance Attribute Summary collapse
-
#body ⇒ Object
readonly
Returns the value of attribute body.
-
#doc ⇒ Object
readonly
Returns the value of attribute doc.
Class Method Summary collapse
-
.inject! ⇒ Object
Inject to_toml methods into the Ruby classes used by TOML (booleans, String, Numeric, Array).
Instance Method Summary collapse
-
#format(val) ⇒ Object
Returns the value formatted for TOML.
-
#initialize(doc) ⇒ Generator
constructor
A new instance of Generator.
- #visit(hash, path = "") ⇒ Object
Constructor Details
#initialize(doc) ⇒ Generator
Returns a new instance of Generator.
6 7 8 9 10 11 12 13 14 15 16 17 |
# File 'lib/toml/generator.rb', line 6 def initialize(doc) # Ensure all the to_toml methods are injected into the base Ruby classes # used by TOML. self.class.inject! @body = "" @doc = doc visit(@doc) return @body end |
Instance Attribute Details
#body ⇒ Object (readonly)
Returns the value of attribute body.
4 5 6 |
# File 'lib/toml/generator.rb', line 4 def body @body end |
#doc ⇒ Object (readonly)
Returns the value of attribute doc.
4 5 6 |
# File 'lib/toml/generator.rb', line 4 def doc @doc end |
Class Method Details
.inject! ⇒ Object
Inject to_toml methods into the Ruby classes used by TOML (booleans, String, Numeric, Array). You can add to_toml methods to your own classes to allow them to be easily serialized by the generator (and it will shout if something doesn’t have a to_toml method).
25 26 27 28 29 |
# File 'lib/toml/generator.rb', line 25 def self.inject! return if @@injected require 'toml/monkey_patch' @@injected = true end |
Instance Method Details
#format(val) ⇒ Object
Returns the value formatted for TOML.
72 73 74 |
# File 'lib/toml/generator.rb', line 72 def format(val) val.to_toml end |
#visit(hash, path = "") ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/toml/generator.rb', line 31 def visit(hash, path = "") hash_pairs = [] # Sub-hashes other_pairs = [] hash.keys.sort.each do |key| val = hash[key] # TODO: Refactor for other hash-likes (OrderedHash) if val.is_a? Hash hash_pairs << [key, val] else other_pairs << [key, val] end end # Handle all the key-values if !path.empty? && !other_pairs.empty? @body += "[#{path}]\n" end other_pairs.each do |pair| key, val = pair if key.include? '.' raise SyntaxError, "Periods are not allowed in keys (failed on key: #{key.inspect})" end unless val.nil? @body += "#{key} = #{format(val)}\n" end end @body += "\n" unless other_pairs.empty? # Then deal with sub-hashes hash_pairs.each do |pair| key, hash = pair if hash.empty? @body += "[#{path.empty? ? key : [path, key].join(".")}]\n" else visit(hash, (path.empty? ? key : [path, key].join("."))) end end end |