Parent

Files

TOML::Generator

Attributes

body[R]
doc[R]

Public Class Methods

inject!() click to toggle source

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).

# File lib/toml/generator.rb, line 25
def self.inject!
  return if @@injected
  require 'toml/monkey_patch'
  @@injected = true
end
new(doc) click to toggle source
# 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

Public Instance Methods

format(val) click to toggle source

Returns the value formatted for TOML.

# File lib/toml/generator.rb, line 72
def format(val)
  val.to_toml
end
visit(hash, path = "") click to toggle source
# 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#visit

[Validate]

Generated with the Darkfish Rdoc Generator 2.