module Roo::Utils
Public Instance Methods
each_element(path, elements) { |XML(outer_xml).root| ... }
click to toggle source
Yield each element of a given type (‘row’, ‘c’, etc.) to caller
# File lib/roo/utils.rb, line 71 def each_element(path, elements) Nokogiri::XML::Reader(::File.open(path, 'rb'), nil, nil, Nokogiri::XML::ParseOptions::NOBLANKS).each do |node| next unless node.node_type == Nokogiri::XML::Reader::TYPE_ELEMENT && Array(elements).include?(node.name) yield Nokogiri::XML(node.outer_xml).root if block_given? end end
letter_to_number(letters)
click to toggle source
# File lib/roo/utils.rb, line 42 def letter_to_number(letters) @letter_to_number ||= {} @letter_to_number[letters] ||= begin result = 0 # :bytes method returns an enumerator in 1.9.3 and an array in 2.0+ letters.bytes.to_a.map{|b| b > 96 ? b - 96 : b - 64 }.reverse.each_with_index{ |num, i| result += num * 26 ** i } result end end
load_xml(path)
click to toggle source
# File lib/roo/utils.rb, line 64 def load_xml(path) ::File.open(path, 'rb') do |file| ::Nokogiri::XML(file) end end
num_cells_in_range(str)
click to toggle source
Compute upper bound for cells in a given cell range.
# File lib/roo/utils.rb, line 55 def num_cells_in_range(str) cells = str.split(':') return 1 if cells.count == 1 raise ArgumentError.new("invalid range string: #{str}. Supported range format 'A1:B2'") if cells.count != 2 x1, y1 = split_coordinate(cells[0]) x2, y2 = split_coordinate(cells[1]) (x2 - (x1 - 1)) * (y2 - (y1 - 1)) end
number_to_letter(num)
click to toggle source
convert a number to something like ‘AB’ (1 => ‘A’, 2 => ‘B’, …)
# File lib/roo/utils.rb, line 29 def number_to_letter(num) results = [] num = num.to_i while (num > 0) mod = (num - 1) % 26 results = [(65 + mod).chr] + results num = ((num - mod) / 26) end results.join end
split_coord(s)
click to toggle source
# File lib/roo/utils.rb, line 18 def split_coord(s) if s =~ /([a-zA-Z]+)([0-9]+)/ letter = Regexp.last_match[1] number = Regexp.last_match[2].to_i else fail ArgumentError end [letter, number] end
split_coordinate(str)
click to toggle source
# File lib/roo/utils.rb, line 5 def split_coordinate(str) @split_coordinate ||= {} @split_coordinate[str] ||= begin letter, number = split_coord(str) x = letter_to_number(letter) y = number [y, x] end end
Also aliased as: ref_to_key