class Terse::Format

Simple class for formatting the list of lines

Public Class Methods

indent(lines, settings) click to toggle source

Apply indentation It is easier to do this once the full list of newlines is assembled

# File lib/terse/format.rb, line 8
def self.indent lines, settings
    indented_lines = []
    indent_level = 0
    lines.each do |l|
        l.strip!
        l =~ settings.indent_out_regex

        # check for a loop-ending before indenting
        indent_level -= 1 if settings.indent_out.include?($1.to_s.strip) # must to_s in case $1 is nil
        indent_level.times do
            l.insert(0, "\t")
        end
        indented_lines << l.dup # need to call .dup ; it will otherwise mess up indentation of loop-ending lines
        
        # check for indent-increasing keywords after indenting
        l =~ settings.indent_in_regex
        indent_level += 1 if settings.indent_in.include?($1.to_s.strip) # must to_s in case $1 is nil
    end
    indented_lines
end
space_lines(lines, keywords, settings) click to toggle source

Insert empty lines in between the end of a method and the start of the next (same for classes & modules)

# File lib/terse/format.rb, line 30
def self.space_lines lines, keywords, settings
    spaced_lines = []
    
    # Filter out keywords that do not trigger some sort of indent-change
    keys = keywords.dup
    keys = keys.delete_if {|k| !(k.needs_top_level_end || k.needs_inner_end)}
    keys.collect! {|k| k.substitute}
    first_word_regex = /^\s*([a-zA-Z0-9_]+)(\s+|$)/
    for i in 0 ... lines.size - 1 
        first_line = lines[i]
        next_line = lines[i + 1]
        
        spaced_lines << first_line
        
        first_line =~ first_word_regex # set the $ variables for inspection
        # We only care about line-pairs where the first line is an end, and the next one matches one of our keys
        if $1.to_s.strip == settings.loop_ending.strip    
            next_line =~ first_word_regex
            spaced_lines << "" if keys.include?($1.to_s.strip)
        end 
    end
    # Remember to add the last line!
    spaced_lines << lines[-1]    
    spaced_lines
end