diff --git a/README.md b/README.md index 72a4d41..e3e6852 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,32 @@ padding-inline-end: 10px; border-inline-start: 1px; ``` +## Configuration + +To use this gem with custom configuration, use the following syntax and pass +options while creating an instance of bidifier: + +```rb +options = { + # ... +} + +bidifier = Bidify::HtmlStringBidifier.new(options) + +puts bidifier.apply('
input stringified html
') +``` + +### Options + +The following is the list of options with their default values +- `greedy: false` + + By default, bidification stops when it reaches an element that has `dir` + attribute. Use `true` to disregard any existing `dir` attributes. +- `with_table_support: false` + + Use `true` to add table tags support. + ## License This project is a Free/Libre and Open Source software released under LGPLv3 license. diff --git a/lib/bidify/bidifier.rb b/lib/bidify/bidifier.rb index af84a93..b32f7d9 100644 --- a/lib/bidify/bidifier.rb +++ b/lib/bidify/bidifier.rb @@ -29,6 +29,8 @@ def bidify_recursively(html_node, options = {}) seen_the_first_bidifiable_element = false html_node.children.each do |child_node| + next if stop_recursion_at?(child_node) + bidify_recursively(child_node) if (options[:root] || seen_the_first_bidifiable_element) && @bidifiable_tags.include?(child_node.name) @@ -42,5 +44,11 @@ def bidify_recursively(html_node, options = {}) def actual_content?(node) node.element? || (node.text? && !node.blank?) end + + def stop_recursion_at?(node) + return false if @options[:greedy] == true + + node.has_attribute?('dir') + end end end diff --git a/spec/html_string_bidifier_spec.rb b/spec/html_string_bidifier_spec.rb index 835ec2a..804bdef 100644 --- a/spec/html_string_bidifier_spec.rb +++ b/spec/html_string_bidifier_spec.rb @@ -179,6 +179,32 @@ expect(actual_output).to eq expected_output end + + it 'stops recursive bidification on an element with explicit dir attribute' do + input = <<~HTML +
+

Item 1

+
+

Item 2

+

Item 3

+
+
+ HTML + + expected_output = <<~HTML +
+

Item 1

+
+

Item 2

+

Item 3

+
+
+ HTML + + actual_output = bidifier.apply(input) + + expect(actual_output).to eq expected_output + end end it 'bidifies a table with :with_table_support option' do @@ -205,4 +231,31 @@ expect(actual_output).to eq expected_output end + + it 'with `greedy: true` option, it disregard any exisitng dir attribute' do + input = <<~HTML +
+

Item 1

+
+

Item 2

+

Item 3

+
+
+ HTML + + expected_output = <<~HTML +
+

Item 1

+
+

Item 2

+

Item 3

+
+
+ HTML + + bidifier = Bidify::HtmlStringBidifier.new(greedy: true) + actual_output = bidifier.apply(input) + + expect(actual_output).to eq expected_output + end end