aboutsummaryrefslogtreecommitdiffstats
path: root/actiontext/lib/action_text/fragment.rb
blob: af276b2b265fa4c39bfc3e667f6615255db35a06 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# frozen_string_literal: true

module ActionText
  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(ActionText::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