lib/fd.rb in fd-0.3.0 vs lib/fd.rb in fd-0.3.1
- old
+ new
@@ -7,11 +7,11 @@
class Fd
class Error < StandardError; end
attr_reader :line_length, :char_table
- # _line_length_ sets how many characters are displayed per line.
+ # _line_length_ sets how many characters are displayed per @line.
# Some <i>special non-printable/invisible characters</i> are displayed as their names.
#
# Name :: Char val
# NULL :: 0
# BEL :: 7
@@ -48,41 +48,56 @@
def dump(file_name)
puts file_name
content = File.read(file_name)
raise "Not the expected encoding of UFT-8, got #{content.encoding}" unless content.encoding == Encoding::UTF_8
- chars = content.chars
- byte_count_in_line = 0
- line = ''
- hex_values = []
- char_index = 0
- while char_index < chars.size
- char = chars[char_index]
- bytes = char.bytes
- if enough_space_in_line?(byte_count_in_line, bytes)
- # Next char fits in line => Add hex values & character to line
- byte_count_in_line += bytes.size
- bytes.each { |bt| hex_values << format('%02x', bt) }
- line += format('%5s', (char_table[char.ord] || char))
- char_index += 1
- else
- # Print a new line…
- print_single_line(hex_values, line)
- # …and reset line internal values
- byte_count_in_line = 0
- hex_values.clear
- line = ''
- end
+ initialize_fields(content)
+ while @char_index < @chars.size
+ process_current_character
end
- print_single_line(hex_values, line) unless line.empty?
+ print_single_line unless line.empty?
end
private
+ def process_current_character
+ char = @chars[@char_index]
+ bytes = char.bytes
+ if enough_space_in_line?(@byte_count_in_line, bytes)
+ append_to_line(bytes, char)
+ else
+ print_single_line
+ reset_line
+ end
+ end
+
+ def initialize_fields(content)
+ @chars = content.chars
+ @byte_count_in_line = 0
+ @line = ''
+ @hex_values = []
+ @char_index = 0
+ end
+
+ attr_reader :hex_values, :line
+
+ def reset_line
+ @byte_count_in_line = 0
+ @hex_values.clear
+ @line = ''
+ end
+
+ def append_to_line(bytes, char)
+ @byte_count_in_line += bytes.size
+ bytes.each { |bt| @hex_values << format('%02x', bt) }
+ @line += format('%5s', (char_table[char.ord] || char))
+ @char_index += 1
+ end
+
def enough_space_in_line?(byte_count_in_line, bytes)
byte_count_in_line + bytes.size <= line_length
end
- def print_single_line(hex_values, line)
+ def print_single_line
puts("#{format("%#{(3 * line_length) - 1}s", hex_values.join(' '))} |#{format("%#{5 * line_length}s", line)}")
end
end