Class: Spacer

Inherits:
Object
  • Object
show all
Defined in:
lib/spacify.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, options = {}) ⇒ Spacer

Returns a new instance of Spacer.



103
104
105
106
107
108
109
# File 'lib/spacify.rb', line 103

def initialize input, options = {}
  @line_regexp = options.delete(:html)
  @io = StringIO.new input
  @lines = []

  parse!
end

Instance Attribute Details

#linesObject

Returns the value of attribute lines.



101
102
103
# File 'lib/spacify.rb', line 101

def lines
  @lines
end

Instance Method Details

#collate_attributes!Object



136
137
138
139
140
141
142
143
144
145
# File 'lib/spacify.rb', line 136

def collate_attributes!
  @attribute_counts  = {}
  @attribute_counts.default = 0
  parsable_lines do |line|
    attributes = line.attributes.to_a
    attributes.each do |attribute|
      @attribute_counts[attribute.attribute_name.to_s] += 1
    end
  end
end

#find_longest_value_for(attribute_name) ⇒ Object



173
174
175
176
177
178
179
180
181
182
183
# File 'lib/spacify.rb', line 173

def find_longest_value_for attribute_name
  longest = 0
  parsable_lines do |line|
    attributes = line.attributes.to_hash
    if attributes[attribute_name]
      attribute_value = attributes[attribute_name].to_s
      longest = attribute_value.size if attribute_value.size > longest
    end
  end
  longest + 1
end

#find_longest_values!Object



162
163
164
165
166
167
168
169
170
171
# File 'lib/spacify.rb', line 162

def find_longest_values!
  @longest_attribute_values = {}
  @attribute_counts.each do |attribute_name, count|
    @longest_attribute_values.update attribute_name => find_longest_value_for( attribute_name )
  end

  lines.each do |line|
    line.attribute_padding_by_name = @longest_attribute_values
  end
end

#parsable_linesObject



185
186
187
188
189
# File 'lib/spacify.rb', line 185

def parsable_lines
  lines.each {|line|
    yield line if line.parse?
  }
end

#read_lines!Object



125
126
127
128
129
130
131
132
133
134
# File 'lib/spacify.rb', line 125

def read_lines!
  @io.each_line do |line|
    if line =~ Regexp.new( @line_regexp )
      parse_line = SpacerLine.new line, @line_regexp
    else
      parse_line = RawLine.new line 
    end
    lines << parse_line
  end
end

#sort_attribute_counts!Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/spacify.rb', line 147

def sort_attribute_counts!
  @attribute_counts = @attribute_counts.sort do |(lkey, lval), (rkey, rval)| 
    comp = rval <=> lval 
    if comp == 0
      lkey <=> rkey
    else
      comp
    end
  end
  
  lines.each do |line|
    line.attribute_sort_order = @attribute_counts
  end
end

#to_sObject



119
120
121
122
123
# File 'lib/spacify.rb', line 119

def to_s
  lines.inject('') do |m, line|
    m += line.to_s
  end
end