Module: Sheng::Support
- Defined in:
- lib/sheng/support.rb
Constant Summary collapse
- NUMERIC_REGEX =
/^(0|[1-9][0-9]*|[1-9][0-9]{0,2}(,[0-9]{3,3})*)(\.[0-9]+)?$/
Class Method Summary collapse
- .extract_mergefield_instruction_text(element) ⇒ Object
- .is_numeric?(value) ⇒ Boolean
- .merge_required_hashes(hsh1, hsh2) ⇒ Object
- .new_tag(tag_name, xml_document:) ⇒ Object
- .new_text_run(value, xml_document:, style_run: nil, space_preserve: false) ⇒ Object
- .typecast_numeric(value) ⇒ Object
Class Method Details
.extract_mergefield_instruction_text(element) ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/sheng/support.rb', line 38 def extract_mergefield_instruction_text(element) if element.name == 'fldSimple' label = element['w:instr'] else current_element = element.parent.next_element label = current_element.at_xpath(".//w:instrText").text loop do current_element = current_element.next_element next if ["bookmarkStart", "bookmarkEnd"].include?(current_element.name) label_part = current_element.at_xpath(".//w:instrText") break unless label_part label << label_part.text end end unless label.match(MergeField::REGEXES[:instruction_text]) raise MergeField::NotAMergeFieldError.new(label) end label end |
.is_numeric?(value) ⇒ Boolean
58 59 60 |
# File 'lib/sheng/support.rb', line 58 def is_numeric?(value) value.is_a?(Numeric) || !!NUMERIC_REGEX.match(value) end |
.merge_required_hashes(hsh1, hsh2) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 |
# File 'lib/sheng/support.rb', line 6 def merge_required_hashes(hsh1, hsh2) hsh1.merge(hsh2) do |key, old_value, new_value| if [old_value, new_value].all? { |v| v.is_a?(Hash) } merge_required_hashes(old_value, new_value) elsif [old_value, new_value].all? { |v| v.is_a?(Array) } && !old_value.empty? [merge_required_hashes(old_value.first, new_value.first)] else new_value end end end |
.new_tag(tag_name, xml_document:) ⇒ Object
32 33 34 35 36 |
# File 'lib/sheng/support.rb', line 32 def new_tag(tag_name, xml_document:) tag = Nokogiri::XML::Node.new(tag_name, xml_document) tag.namespace = xml_document.root.namespace_definitions.find { |ns| ns.prefix == "w" } tag end |
.new_text_run(value, xml_document:, style_run: nil, space_preserve: false) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/sheng/support.rb', line 18 def new_text_run(value, xml_document:, style_run: nil, space_preserve: false) r_tag = new_tag('r', xml_document: xml_document) if style_run r_tag.add_child(style_run) end t_tag = new_tag('t', xml_document: xml_document) if space_preserve t_tag["xml:space"] = "preserve" end t_tag.content = value r_tag.add_child(t_tag) r_tag end |
.typecast_numeric(value) ⇒ Object
62 63 64 65 66 67 68 69 70 |
# File 'lib/sheng/support.rb', line 62 def typecast_numeric(value) return value if value.is_a?(Numeric) || !NUMERIC_REGEX.match(value) val = value.gsub(",", "").to_d if val.frac == 0 val.to_i else val end end |