class Guard::Yamlsort::FileSorter

Attributes

yaml[RW]

Public Class Methods

new(path, start_on_init = true) click to toggle source

Initialized with the path of the YAML file we want to sort. It automatically loads the file, stores any comments in memory, and then starts sorting unless otherwise specified with the start_on_init parameter. If no parameters are passed a Generic

@param path [String] the path on disc this file is located at @param start_on_init [Boolean] whether or not to automatically sort & write on

initialization of a FileSorter (for testing purposes)
# File lib/guard/yamlsort/file_sorter.rb, line 14
def initialize(path, start_on_init = true)
  @path = path
  @comments = []
  load_yaml 
  sort_yaml
  write_yaml
end
sort(obj) click to toggle source

Recursively sorts any hash it's given by key using Array#sort

# File lib/guard/yamlsort/file_sorter.rb, line 51
def self.sort(obj)
  if obj.is_a? Hash
    sorted = {}
    obj.keys.sort.each { |k| sorted[k] = sort(obj[k]) }
    sorted
  else 
    return obj
  end
end

Public Instance Methods

load_yaml() click to toggle source

Load the YAML file contents into @yaml and store the comments in @comments

# File lib/guard/yamlsort/file_sorter.rb, line 23
def load_yaml
  self.yaml= File.open(@path, "r") do |f| 
    contents = f.read
    contents.split("\n").each do |line|
      @comments.push(line) if line[0] == '#'
    end
    YAML.load(contents) 
  end
end
sort_yaml() click to toggle source

Recursively sort the contents of @yaml

# File lib/guard/yamlsort/file_sorter.rb, line 34
def sort_yaml
  self.yaml= self.class.sort(yaml)
end
write_yaml() click to toggle source

Sorts the hash alphabetically by it's keys and then writes the original comments plus the sorted hash to the same path in a valid YAML file.

# File lib/guard/yamlsort/file_sorter.rb, line 40
def write_yaml
  File.open(@path, "w") do |f| 
    if !@comments.empty?
      f.write @comments.join("\n")
      f.write("\n")
    end
    f.write YAML.dump(yaml)
  end
end