url_extract 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UrlExtract
4
+ module Trimming # :nodoc: all
5
+ # Returns the count of the bytes of the string that ends a URL, for the strings of the `trim` list
6
+ # that have more than one byte, such as `...` or `»`. Returns 0 when no string ends the URL.
7
+ # When more than one string ends the URL, it takes the longest.
8
+ #
9
+ # It compares the bytes of each string with the last bytes of the URL, and makes no object.
10
+ class EndingStringSize # :nodoc: all
11
+ def initialize(strings)
12
+ longest_first_strings = strings.sort_by { |string| -string.bytesize }
13
+ @byte_sequences = longest_first_strings.map { |string| string.bytes.freeze }.freeze
14
+ freeze
15
+ end
16
+
17
+ # The URL is the bytes of the text from `start` to `finish`.
18
+ # The loops are `while` loops: a `return` out of a block makes an object.
19
+ def call(text, start, finish)
20
+ byte_sequences = @byte_sequences
21
+ count = byte_sequences.size
22
+ index = 0
23
+
24
+ while index < count
25
+ bytes = byte_sequences[index]
26
+ return bytes.size if ends_with?(text, start, finish, bytes)
27
+
28
+ index += 1
29
+ end
30
+
31
+ 0
32
+ end
33
+
34
+ private
35
+
36
+ def ends_with?(text, start, finish, bytes)
37
+ size = bytes.size
38
+ string_start = finish - size
39
+ return false if string_start < start
40
+
41
+ index = 0
42
+ index += 1 while (index < size) && (text.getbyte(string_start + index) == bytes[index])
43
+
44
+ index == size
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UrlExtract
4
+ module Trimming # :nodoc: all
5
+ # Returns the byte index after the last closing bracket of a URL that has a partner.
6
+ # Returns `start` when no closing bracket has a partner.
7
+ # The URL is the bytes of the text from `start` to `finish`.
8
+ #
9
+ # A closing bracket has a partner when an opening bracket of its kind is open before it:
10
+ # - `x_(y)` gives the index after the `)`
11
+ # - `x_(y))` gives the index after the first `)`: nothing opens the second
12
+ # - `x)(` gives `start`: the `)` comes before the `(`
13
+ #
14
+ # Each kind of bracket has its own count, so `x([y)]` has two closing brackets with a partner.
15
+ # Each bracket after the returned index has no partner: a closing bracket that nothing opens,
16
+ # or an opening bracket that nothing closes.
17
+ #
18
+ # It reads the bytes of the URL one time, and keeps one count for each kind of bracket.
19
+ # Thus the time is linear, and it makes no object.
20
+ class IndexAfterLastPairedBracket # :nodoc: all
21
+ ROUND_OPENING = "(".ord
22
+ ROUND_CLOSING = ")".ord
23
+ SQUARE_OPENING = "[".ord
24
+ SQUARE_CLOSING = "]".ord
25
+ CURLY_OPENING = "{".ord
26
+ CURLY_CLOSING = "}".ord
27
+
28
+ class << self
29
+ # The counts are locals of one method: an array or an object for them costs an allocation for each URL.
30
+ def call(text, start, finish)
31
+ round_count = square_count = curly_count = 0
32
+ after_last_pair = start
33
+ index = start
34
+
35
+ while index < finish
36
+ case text.getbyte(index)
37
+ when ROUND_OPENING then round_count += 1
38
+ when SQUARE_OPENING then square_count += 1
39
+ when CURLY_OPENING then curly_count += 1
40
+ when ROUND_CLOSING
41
+ if round_count.positive?
42
+ round_count -= 1
43
+ after_last_pair = index + 1
44
+ end
45
+ when SQUARE_CLOSING
46
+ if square_count.positive?
47
+ square_count -= 1
48
+ after_last_pair = index + 1
49
+ end
50
+ when CURLY_CLOSING
51
+ if curly_count.positive?
52
+ curly_count -= 1
53
+ after_last_pair = index + 1
54
+ end
55
+ end
56
+
57
+ index += 1
58
+ end
59
+
60
+ after_last_pair
61
+ end
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UrlExtract
4
+ module Trimming # :nodoc: all
5
+ # Finds how much of a URL in a text stays, when the end of the URL belongs to the text around it. It removes:
6
+ # - each string of the list, such as the dot of `See https://example.com/x.`
7
+ # - with `trim_html_entities`, an HTML entity, such as the `&quot;` of `https://example.com/x&quot;`
8
+ # - with `trim_brackets`, a bracket with no partner, as `IndexAfterLastPairedBracket` says:
9
+ # the `)` of `(https://example.com/x)` and the `(` of `https://example.com/x( see)`. A bracket with a partner stays,
10
+ # as in `https://example.com/x_(y)`.
11
+ #
12
+ # It repeats these until the last character of the URL stays.
13
+ # An HTML entity is one unit: without `trim_html_entities` it stays, and the `;` of the list does not cut its end.
14
+ #
15
+ # It works with byte indexes in the text, and reads the last byte of the URL first.
16
+ # A string of one byte, an HTML entity and a bracket make no object.
17
+ # `Validations::Options` checks the options before.
18
+ class Trim # :nodoc: all
19
+ BRACKETS = "()[]{}"
20
+
21
+ def initialize(trim:, trim_html_entities:, trim_brackets:)
22
+ one_byte_strings, multibyte_strings = trim.partition { |string| string.bytesize == 1 }
23
+ @one_byte_table = byte_table(one_byte_strings.map(&:ord))
24
+ @bracket_table = byte_table(trim_brackets ? BRACKETS.bytes : [])
25
+ @trim_html_entities = trim_html_entities
26
+ @ending_string_size = EndingStringSize.new(multibyte_strings)
27
+ freeze
28
+ end
29
+
30
+ # Returns the end of the URL that stays, of the URL that is the bytes of the text from `start` to `finish`.
31
+ def call(text, start, finish)
32
+ finish = strip(text, start, finish)
33
+ finish = strip_brackets(text, start, finish) if ends_with_bracket?(text, start, finish)
34
+
35
+ finish
36
+ end
37
+
38
+ private
39
+
40
+ def byte_table(bytes)
41
+ table = Array.new(256, false)
42
+ bytes.each { |byte| table[byte] = true }
43
+ table.freeze
44
+ end
45
+
46
+ # Removes each string of the list, and each HTML entity, at the end of the URL.
47
+ # Returns the new end of the URL.
48
+ # The loops of this class are `while` loops: a `return` out of a `loop` block makes an object.
49
+ def strip(text, start, finish)
50
+ ending_size = ending_size(text, start, finish)
51
+
52
+ until ending_size.zero?
53
+ finish -= ending_size
54
+ ending_size = ending_size(text, start, finish)
55
+ end
56
+
57
+ finish
58
+ end
59
+
60
+ def ends_with_bracket?(text, start, finish)
61
+ (finish > start) && @bracket_table[text.getbyte(finish - 1)]
62
+ end
63
+
64
+ # Removes each bracket with no partner at the end of the URL, and what `strip` removes before it.
65
+ # Each bracket after the last closing bracket with a partner has no partner.
66
+ def strip_brackets(text, start, finish)
67
+ after_last_pair = IndexAfterLastPairedBracket.call(text, start, finish)
68
+ while (finish > after_last_pair) && ends_with_bracket?(text, start, finish)
69
+ finish = strip(text, start, finish - 1)
70
+ end
71
+
72
+ finish
73
+ end
74
+
75
+ # Returns the count of the bytes to remove from the end of the URL, or 0.
76
+ def ending_size(text, start, finish)
77
+ return 0 if finish == start
78
+
79
+ entity_size = EndingEntitySize.call(text, start, finish)
80
+ return (@trim_html_entities ? entity_size : 0) if entity_size.positive?
81
+
82
+ string_size = @ending_string_size.call(text, start, finish)
83
+ return string_size if string_size.positive?
84
+
85
+ @one_byte_table[text.getbyte(finish - 1)] ? 1 : 0
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UrlExtract
4
+ module Validations # :nodoc: all
5
+ # Raises the error of a value that the extractor can not take. Its message has two lines: what is wrong,
6
+ # and a short hint of what to provide.
7
+ #
8
+ # Invalid value for trim: "." provided
9
+ # [hint] Provide array of strings like ["?", "!", ".", ",", ":", ";", "*", "_", "~"]
10
+ class Failure # :nodoc: all
11
+ # The longest part of a wrong value that an error shows. The value can be a long text, given by mistake.
12
+ MAX_SHOWN_SIZE = 60
13
+
14
+ class << self
15
+ def fail_with(message, hint, error_class: ArgumentError)
16
+ raise error_class, "#{message}\n[hint] #{hint}"
17
+ end
18
+
19
+ # Shows a value in a message: the result of `inspect`, cut to `MAX_SHOWN_SIZE` characters.
20
+ def show(value)
21
+ shown = value.inspect
22
+ (shown.length > MAX_SHOWN_SIZE) ? "#{shown[0, MAX_SHOWN_SIZE]}..." : shown
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UrlExtract
4
+ module Validations # :nodoc: all
5
+ # Checks the options of `UrlExtract.new`: each name, and the type and the value of each option.
6
+ # A wrong option raises `ArgumentError`, with a hint of what to provide:
7
+ #
8
+ # UrlExtract.scan(text, trim: ".")
9
+ # # ArgumentError: Invalid value for trim: "." provided
10
+ # # [hint] Provide array of strings like ["?", "!", ".", ",", ":", ";", "*", "_", "~"]
11
+ class Options # :nodoc: all
12
+ ON_ENCODING_ERROR = %i[warn skip raise].freeze
13
+ # The private method that checks each option: `check_` and the name of the option.
14
+ CHECK_METHODS = DEFAULTS.keys.to_h { |name| [name, :"check_#{name}"] }.freeze
15
+
16
+ class << self
17
+ def check(options)
18
+ check_names(options.keys)
19
+
20
+ # `check_names` lets only the names of `CHECK_METHODS` through.
21
+ options.each { |name, value| send(CHECK_METHODS[name], value) }
22
+ end
23
+
24
+ private
25
+
26
+ def check_names(names)
27
+ unknown_names = names - DEFAULTS.keys
28
+ return if unknown_names.empty?
29
+
30
+ label = unknown_names.one? ? "option" : "options"
31
+ Failure.fail_with("Unknown #{label} #{unknown_names.map { |name| Failure.show(name) }.join(", ")}",
32
+ "Allowed options: #{DEFAULTS.keys.map(&:inspect).join(", ")}")
33
+ end
34
+
35
+ def check_prefixes(prefixes)
36
+ check_array(:prefixes, prefixes)
37
+
38
+ prefixes.each do |prefix|
39
+ check_string("prefix", prefix, %("https://" or "www."))
40
+ if prefix.match?(/[[:space:]]/)
41
+ Failure.fail_with("Invalid prefix: #{Failure.show(prefix)} provided", "Remove the spaces")
42
+ end
43
+ # A start such as `https` holds no `:` and no `.`, so it starts a URL only in a word such as `httpsx`.
44
+ if prefix.match?(/\A[[:alnum:]+-]+\z/)
45
+ Failure.fail_with("Invalid prefix: #{Failure.show(prefix)} provided",
46
+ %(End it with "://" or ".", like "https://" or "www."))
47
+ end
48
+ end
49
+ end
50
+
51
+ def check_max_bytesize(max_bytesize)
52
+ return if max_bytesize.nil? || (max_bytesize.is_a?(Integer) && max_bytesize.positive?)
53
+
54
+ Failure.fail_with("Invalid value for max_bytesize: #{Failure.show(max_bytesize)} provided",
55
+ "Provide a positive integer like #{DEFAULTS[:max_bytesize]}, or nil for no limit")
56
+ end
57
+
58
+ def check_trim(trim)
59
+ check_array(:trim, trim)
60
+ trim.each { |string| check_string("trim string", string, '"."') }
61
+ end
62
+
63
+ def check_trim_html_entities(value) = check_boolean(:trim_html_entities, value)
64
+
65
+ def check_trim_brackets(value) = check_boolean(:trim_brackets, value)
66
+
67
+ def check_on_encoding_error(value)
68
+ return if ON_ENCODING_ERROR.include?(value)
69
+
70
+ Failure.fail_with("Invalid value for on_encoding_error: #{Failure.show(value)} provided",
71
+ "Provide :warn, :skip or :raise")
72
+ end
73
+
74
+ def check_boolean(name, value)
75
+ return if (value == true) || (value == false)
76
+
77
+ Failure.fail_with("Invalid value for #{name}: #{Failure.show(value)} provided", "Provide true or false")
78
+ end
79
+
80
+ def check_array(name, value)
81
+ return if value.is_a?(Array)
82
+
83
+ Failure.fail_with("Invalid value for #{name}: #{Failure.show(value)} provided",
84
+ "Provide array of strings like #{DEFAULTS[name].inspect}")
85
+ end
86
+
87
+ def check_string(label, string, example)
88
+ unless string.is_a?(String) && !string.empty?
89
+ Failure.fail_with("Invalid #{label}: #{Failure.show(string)} provided",
90
+ "Provide a non-empty string like #{example}")
91
+ end
92
+ return if utf8?(string)
93
+
94
+ Failure.fail_with("Invalid #{label}: #{Failure.show(string)} provided", "Provide a UTF-8 string")
95
+ end
96
+
97
+ # The extractor compares the bytes of the string with the bytes of a UTF-8 text: a string in another
98
+ # encoding, such as `"»"` in Windows-1251, would cut a byte of a character from the end of a URL.
99
+ # A string of ASCII characters only reads the same in each encoding that is compatible with ASCII.
100
+ def utf8?(string)
101
+ string.valid_encoding? && ((string.encoding == Encoding::UTF_8) || string.ascii_only?)
102
+ end
103
+ end
104
+ end
105
+ end
106
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UrlExtract
4
+ module Validations # :nodoc: all
5
+ # Checks the text of an extractor. A text that is not a string raises `TypeError`, and a text that
6
+ # the extractor can not read as UTF-8 raises `UrlExtract::EncodingError`, which `on_encoding_error` handles.
7
+ class Text # :nodoc: all
8
+ class << self
9
+ # The text: a string of valid bytes, in UTF-8 or in another encoding, which `Input::Encodings` reads.
10
+ # `valid_encoding?` reads a large text fast, and Ruby keeps its result in the string.
11
+ # The index of the invalid byte costs more, so only the error looks for it.
12
+ def check(text)
13
+ unless text.is_a?(String)
14
+ Failure.fail_with("Invalid text: #{Failure.show(text)} provided", "Provide a string",
15
+ error_class: TypeError)
16
+ end
17
+
18
+ fail_unreadable(text, invalid_index(text)) unless text.valid_encoding?
19
+ end
20
+
21
+ # The extractor reads UTF-8. A text of ASCII characters only reads the same in each encoding
22
+ # that is compatible with ASCII, such as a string of bytes.
23
+ def utf8?(text)
24
+ encoding = text.encoding
25
+ (encoding == Encoding::UTF_8) || (encoding == Encoding::US_ASCII) || text.ascii_only?
26
+ end
27
+
28
+ # Raises the error of a text that the extractor can not read as UTF-8, whatever the cause:
29
+ # an invalid byte, a byte that is no character, or an encoding that the extractor can not convert.
30
+ # The index is the index of the character at fault, when one character is at fault.
31
+ # `Input::Encodings` raises its errors here too.
32
+ def fail_unreadable(text, index = nil)
33
+ details = "encoding #{text.encoding}"
34
+ details += ", index #{index}" if index
35
+ Failure.fail_with("Invalid text: can not be read as UTF-8 (#{details})", "Provide a valid UTF-8 string",
36
+ error_class: UrlExtract::EncodingError)
37
+ end
38
+
39
+ private
40
+
41
+ # The index of the first invalid character, in characters, as the index of a match.
42
+ def invalid_index(text)
43
+ text.each_char.find_index { |character| !character.valid_encoding? }
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UrlExtract
4
+ # Version of the gem
5
+ VERSION = File.read(File.join(File.dirname(__FILE__), "../../VERSION")).strip.freeze
6
+ end
@@ -0,0 +1,202 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "strscan"
4
+
5
+ require_relative "url_extract/version"
6
+
7
+ # Finds each URL in a plain text, with its place in the text:
8
+ #
9
+ # ```ruby
10
+ # UrlExtract.scan("See https://example.com/x and https://example.com/x").map(&:url)
11
+ # # => ["https://example.com/x", "https://example.com/x"]
12
+ # ```
13
+ #
14
+ # The URLs are raw: each URL as the text writes it, at each place, so a URL can come more than one time.
15
+ # `UrlExtract.scan` describes the options, and `UrlExtract::Match` describes a match.
16
+ class UrlExtract
17
+ include Enumerable
18
+
19
+ # The error of a text that the extractor can not read as UTF-8: an invalid byte, a byte that is no character,
20
+ # or an encoding that the extractor can not convert.
21
+ #
22
+ # It raises only with `on_encoding_error: :raise`. With the default, `:warn`, such a text gives no match
23
+ # and warns, and with `:skip` it gives no match and says nothing:
24
+ #
25
+ # ```ruby
26
+ # UrlExtract.scan("See https://example.com/x \xFF", on_encoding_error: :raise)
27
+ # # UrlExtract::EncodingError: Invalid text: can not be read as UTF-8 (encoding UTF-8, index 26)
28
+ # # [hint] Provide a valid UTF-8 string
29
+ # ```
30
+ #
31
+ # It is an `ArgumentError`, as Ruby raises for an invalid byte. It is not Ruby's `::EncodingError`.
32
+ class EncodingError < ArgumentError; end
33
+
34
+ # The default options of an extractor. `UrlExtract.scan` describes each option.
35
+ DEFAULTS = {
36
+ prefixes: %w[https:// http://].freeze,
37
+ # RFC 9110 recommends that HTTP software supports a URL of at least 8000 bytes:
38
+ # https://www.rfc-editor.org/rfc/rfc9110#section-4.1
39
+ max_bytesize: 8000,
40
+ # The list of the "Autolinks (extension)" part of the GitHub Flavored Markdown Spec, with `;`:
41
+ # https://github.github.com/gfm/#autolinks-extension-
42
+ trim: %w[? ! . , : ; * _ ~].freeze,
43
+ trim_html_entities: true,
44
+ trim_brackets: true,
45
+ on_encoding_error: :warn
46
+ }.freeze
47
+
48
+ # The longest part of the text that `inspect` shows.
49
+ INSPECTED_TEXT_SIZE = 60
50
+ private_constant :INSPECTED_TEXT_SIZE
51
+
52
+ # call-seq:
53
+ # scan(text, **options) -> url_extract
54
+ #
55
+ # Returns an extractor of the URLs of the text: a `UrlExtract`, which is enumerable.
56
+ # It reads the text only as far as a method of `Enumerable` asks: `first(2)` reads it up to the second URL:
57
+ #
58
+ # ```ruby
59
+ # extractor = UrlExtract.scan("See https://example.com/x, https://example.org/y and https://example.net/z")
60
+ # extractor.map(&:url) # => ["https://example.com/x", "https://example.org/y", "https://example.net/z"]
61
+ # extractor.first(2).map(&:url) # => ["https://example.com/x", "https://example.org/y"]
62
+ # ```
63
+ #
64
+ # `UrlExtract.(text)` is the same:
65
+ #
66
+ # ```ruby
67
+ # UrlExtract.("See https://example.com/x").map(&:url) # => ["https://example.com/x"]
68
+ # ```
69
+ #
70
+ # Each option has its default in `DEFAULTS`.
71
+ #
72
+ # With `prefixes:`, what starts a URL. A prefix with `://` starts a URL at each place. Another prefix,
73
+ # such as `www.`, starts a URL only at the start of a word, before a letter or a digit:
74
+ #
75
+ # ```ruby
76
+ # text = "See www.example.com, localhost:3000/x and https://example.com/x"
77
+ # UrlExtract.scan(text, prefixes: %w[www. localhost: https://]).map(&:url)
78
+ # # => ["www.example.com", "localhost:3000/x", "https://example.com/x"]
79
+ # ```
80
+ #
81
+ # With `max_bytesize:`, the largest size of a URL, in bytes. A longer URL gives no match, and no match
82
+ # for a part of it. `nil` sets no limit:
83
+ #
84
+ # ```ruby
85
+ # text = "See https://example.com/x and https://example.com/very/long/path"
86
+ # UrlExtract.scan(text, max_bytesize: 25).map(&:url) # => ["https://example.com/x"]
87
+ # UrlExtract.scan(text, max_bytesize: nil).map(&:url) # => ["https://example.com/x", "https://example.com/very/long/path"]
88
+ # ```
89
+ #
90
+ # With `trim:`, the strings to remove from the end of a URL. `[]` removes nothing:
91
+ #
92
+ # ```ruby
93
+ # UrlExtract.scan("See https://example.com/x.", trim: []).map(&:url) # => ["https://example.com/x."]
94
+ # UrlExtract.scan("See https://example.com/x...»", trim: ["...", "»"]).map(&:url) # => ["https://example.com/x"]
95
+ # ```
96
+ #
97
+ # With `trim_html_entities: true`, removes an HTML entity from the end of a URL, such as `&quot;`, `&#39;`
98
+ # or `&#x27;`. An entity is one unit: the `;` of the `trim` list does not cut its end. `false` keeps it:
99
+ #
100
+ # ```ruby
101
+ # text = "<p>&quot;https://example.com/x&quot;</p>"
102
+ # UrlExtract.scan(text).map(&:url) # => ["https://example.com/x"]
103
+ # UrlExtract.scan(text, trim_html_entities: false).map(&:url) # => ["https://example.com/x&quot;"]
104
+ # ```
105
+ #
106
+ # With `trim_brackets: true`, removes from the end of a URL a closing bracket that the URL does not open,
107
+ # and an opening bracket that the URL does not close. `false` removes no bracket:
108
+ #
109
+ # ```ruby
110
+ # UrlExtract.scan("(See https://example.com/x) and https://en.wikipedia.org/wiki/Ruby_(programming_language)").map(&:url)
111
+ # # => ["https://example.com/x", "https://en.wikipedia.org/wiki/Ruby_(programming_language)"]
112
+ # UrlExtract.scan("(See https://example.com/x)", trim_brackets: false).map(&:url) # => ["https://example.com/x)"]
113
+ # ```
114
+ #
115
+ # With `on_encoding_error:`, what a text that the extractor can not read as UTF-8 does. It gives no match,
116
+ # and `:warn` warns at the line of the caller, `:skip` says nothing, and `:raise` raises
117
+ # `UrlExtract::EncodingError` instead:
118
+ #
119
+ # ```ruby
120
+ # UrlExtract.scan("See https://example.com/x \xFF").to_a # => []
121
+ # # warning: url_extract: Invalid text: can not be read as UTF-8 (encoding UTF-8, index 26)
122
+ # UrlExtract.scan("See https://example.com/x \xFF", on_encoding_error: :skip).to_a # => []
123
+ # ```
124
+ def self.scan(text, **)
125
+ new(text, **)
126
+ end
127
+
128
+ class << self
129
+ # The same as `UrlExtract.scan`, so `UrlExtract.(text)` works too.
130
+ alias_method :call, :scan
131
+ end
132
+
133
+ # call-seq:
134
+ # new(text, **options) -> url_extract
135
+ #
136
+ # The same as `UrlExtract.scan`.
137
+ def initialize(text, **options)
138
+ @reader = Input::Reader.new(text, Rules.from(options))
139
+ end
140
+
141
+ # call-seq:
142
+ # each {|match| ... } -> self
143
+ # each -> enumerator
144
+ #
145
+ # With a block given, calls the block with each match, when the extractor finds it; returns `self`:
146
+ #
147
+ # ```ruby
148
+ # UrlExtract.scan("See https://example.com/x and https://example.org/y").each { |match| p match.url }
149
+ # # => "https://example.com/x"
150
+ # # => "https://example.org/y"
151
+ # ```
152
+ #
153
+ # With no block given, returns an enumerator:
154
+ #
155
+ # ```ruby
156
+ # UrlExtract.scan("See https://example.com/x and https://example.org/y").each.next.url # => "https://example.com/x"
157
+ # ```
158
+ #
159
+ # Each call reads the text again: call `to_a` to keep the matches.
160
+ def each
161
+ return to_enum(:each) unless block_given?
162
+
163
+ text = @reader.text
164
+ @reader.each_url { |url, index| yield Match.new(url, index, text) }
165
+ self
166
+ end
167
+
168
+ # call-seq:
169
+ # inspect -> string
170
+ #
171
+ # Returns a string that shows the start of the text, and not the rules of the options:
172
+ #
173
+ # ```ruby
174
+ # UrlExtract.scan("See https://example.com/x") # => #<UrlExtract text="See https://example.com/x">
175
+ # ```
176
+ #
177
+ # A text that the extractor can not read shows as nil:
178
+ #
179
+ # ```ruby
180
+ # UrlExtract.scan("\xFF", on_encoding_error: :skip) # => #<UrlExtract text=nil>
181
+ # ```
182
+ def inspect
183
+ shown = @reader.text.inspect
184
+ shown = "#{shown[0, INSPECTED_TEXT_SIZE]}..." if shown.length > INSPECTED_TEXT_SIZE
185
+ "#<#{self.class} text=#{shown}>"
186
+ end
187
+ end
188
+
189
+ require_relative "url_extract/match"
190
+ require_relative "url_extract/scanner"
191
+ require_relative "url_extract/input/encoding_error_policy"
192
+ require_relative "url_extract/input/reader"
193
+ require_relative "url_extract/trimming/ending_entity_size"
194
+ require_relative "url_extract/trimming/ending_string_size"
195
+ require_relative "url_extract/trimming/index_after_last_paired_bracket"
196
+ require_relative "url_extract/trimming/trim"
197
+ require_relative "url_extract/validations/failure"
198
+ require_relative "url_extract/validations/options"
199
+ require_relative "url_extract/validations/text"
200
+
201
+ # Last: it builds the rules of the default options with the classes above.
202
+ require_relative "url_extract/rules"
@@ -0,0 +1,35 @@
1
+ class UrlExtract
2
+ include Enumerable[Match]
3
+
4
+ VERSION: String
5
+
6
+ DEFAULTS: Hash[Symbol, untyped]
7
+
8
+ class EncodingError < ArgumentError
9
+ end
10
+
11
+ def self.scan: (String text, **untyped options) -> UrlExtract
12
+
13
+ alias self.call self.scan
14
+
15
+ def initialize: (String text, **untyped options) -> void
16
+
17
+ def each: () { (Match match) -> void } -> self
18
+ | () -> Enumerator[Match, self]
19
+
20
+ def inspect: () -> String
21
+
22
+ class Match
23
+ attr_reader url: String
24
+
25
+ attr_reader range: Range[Integer]
26
+
27
+ attr_reader text: String
28
+
29
+ def initialize: (String url, Integer index, String text) -> void
30
+
31
+ def to_s: () -> String
32
+
33
+ def inspect: () -> String
34
+ end
35
+ end