Class: TruncateHtml::HtmlString

Inherits:
String
  • Object
show all
Defined in:
lib/truncate_html/html_string.rb

Constant Summary collapse

UNPAIRED_TAGS =
%w(br hr img).freeze
REGEX =
/(?:<script.*>.*<\/script>)+|<\/?[^>]+>|[[[:alpha:]][0-9]\|`~!@#\$%^&*\(\)\-_\+=\[\]{}:;'²³§",\.\/?]+|\s+|[[:punct:]]/.freeze

Instance Method Summary collapse

Constructor Details

#initialize(original_html) ⇒ HtmlString

Returns a new instance of HtmlString.



8
9
10
# File 'lib/truncate_html/html_string.rb', line 8

def initialize(original_html)
  super(original_html)
end

Instance Method Details

#html_comment?Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/truncate_html/html_string.rb', line 32

def html_comment?
  /<\s?!--.*-->/ === self
end

#html_tag?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/truncate_html/html_string.rb', line 24

def html_tag?
  /<\/?[^>]+>/ === self && !html_comment?
end

#html_tokensObject



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/truncate_html/html_string.rb', line 12

def html_tokens
  scan(REGEX).map do |token|
    HtmlString.new(
      token.gsub(
        /\n/,' ' #replace newline characters with a whitespace
      ).gsub(
        /\s+/, ' ' #clean out extra consecutive whitespace
      )
    )
  end
end

#matching_close_tagObject



36
37
38
# File 'lib/truncate_html/html_string.rb', line 36

def matching_close_tag
  gsub(/<(\w+)\s?.*>/, '</\1>').strip
end

#open_tag?Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/truncate_html/html_string.rb', line 28

def open_tag?
  /<(?!(?:#{UNPAIRED_TAGS.join('|')}|script|\/))[^>]+>/i === self
end