Class: OpenStax::Content::Fragment::Html

Inherits:
OpenStax::Content::Fragment show all
Defined in:
lib/openstax/content/fragment/html.rb

Direct Known Subclasses

Embedded, Reading

Instance Attribute Summary collapse

Attributes inherited from OpenStax::Content::Fragment

#labels, #node_id, #title

Instance Method Summary collapse

Constructor Details

#initialize(node:, title: nil, labels: nil) ⇒ Html

Returns a new instance of Html.



8
9
10
11
12
13
# File 'lib/openstax/content/fragment/html.rb', line 8

def initialize(node:, title: nil, labels: nil)
  super

  @node = Nokogiri::HTML.fragment node.to_html
  @to_html = @node.to_html
end

Instance Attribute Details

#to_htmlObject (readonly)

Returns the value of attribute to_html.



6
7
8
# File 'lib/openstax/content/fragment/html.rb', line 6

def to_html
  @to_html
end

Instance Method Details

#append(new_node) ⇒ Object



36
37
38
39
40
# File 'lib/openstax/content/fragment/html.rb', line 36

def append(new_node)
  (node.at_css('body') || node.root) << new_node

  @to_html = node.to_html
end

#as_json(*args) ⇒ Object



15
16
17
18
# File 'lib/openstax/content/fragment/html.rb', line 15

def as_json(*args)
  # Don't attempt to serialize @node (it would fail)
  super.except('node')
end

#blank?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/openstax/content/fragment/html.rb', line 24

def blank?
  !html?
end

#has_css?(css, custom_css) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/openstax/content/fragment/html.rb', line 32

def has_css?(css, custom_css)
  !node.at_css(css, custom_css).nil?
end

#html?Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/openstax/content/fragment/html.rb', line 20

def html?
  !to_html.empty?
end

#nodeObject



28
29
30
# File 'lib/openstax/content/fragment/html.rb', line 28

def node
  @node ||= Nokogiri::HTML.fragment to_html
end

#transform_links!Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/openstax/content/fragment/html.rb', line 42

def transform_links!
  node.css('[href]').each do |link|
    href = link.attributes['href']
    uri = Addressable::URI.parse(href.value) rescue nil

    # Modify only fragment-only links
    next if uri.nil? || uri.absolute? || !uri.path.empty?

    # Abort if there is no target or it contains double quotes
    # or it's still present in this fragment
    target = uri.fragment
    next if target.nil? || target.empty? || target.include?('"') ||
            node.at_css("[id=\"#{target}\"], [name=\"#{target}\"]")

    # Change the link to point to the reference view
    href.value = "#{@reference_view_url}##{target}"
  end unless @reference_view_url.nil?

  @to_html = node.to_html
end