aboutsummaryrefslogtreecommitdiffstats
path: root/lib/active_text/fragment.rb
diff options
context:
space:
mode:
authorSam Stephenson <sam@37signals.com>2018-02-07 18:26:19 -0600
committerSam Stephenson <sam@37signals.com>2018-02-07 18:26:19 -0600
commit68d350ddacedf604717f0d1074d7624fa57757c2 (patch)
treea01852130448e37368ed2fd4af7e930e6c2cd0f2 /lib/active_text/fragment.rb
parente22ba227a694b8426e69dbce640c5b0e4f39f574 (diff)
downloadrails-68d350ddacedf604717f0d1074d7624fa57757c2.tar.gz
rails-68d350ddacedf604717f0d1074d7624fa57757c2.tar.bz2
rails-68d350ddacedf604717f0d1074d7624fa57757c2.zip
Initial import from BC3 RichText
Diffstat (limited to 'lib/active_text/fragment.rb')
-rw-r--r--lib/active_text/fragment.rb55
1 files changed, 55 insertions, 0 deletions
diff --git a/lib/active_text/fragment.rb b/lib/active_text/fragment.rb
new file mode 100644
index 0000000000..9e0af6f57a
--- /dev/null
+++ b/lib/active_text/fragment.rb
@@ -0,0 +1,55 @@
+module ActiveText
+ class Fragment
+ class << self
+ def wrap(fragment_or_html)
+ case fragment_or_html
+ when self
+ fragment_or_html
+ when Nokogiri::HTML::DocumentFragment
+ new(fragment_or_html)
+ else
+ from_html(fragment_or_html)
+ end
+ end
+
+ def from_html(html)
+ new(ActiveText::HtmlConversion.fragment_for_html(html.to_s.strip))
+ end
+ end
+
+ attr_reader :source
+
+ def initialize(source)
+ @source = source
+ end
+
+ def find_all(selector)
+ source.css(selector)
+ end
+
+ def update
+ yield source = self.source.clone
+ self.class.new(source)
+ end
+
+ def replace(selector)
+ update do |source|
+ source.css(selector).each do |node|
+ node.replace(yield(node).to_s)
+ end
+ end
+ end
+
+ def to_plain_text
+ @plain_text ||= PlainTextConversion.node_to_plain_text(source)
+ end
+
+ def to_html
+ @html ||= HtmlConversion.node_to_html(source)
+ end
+
+ def to_s
+ to_html
+ end
+ end
+end