lib/to_regexp.rb in to_regexp-0.1.1 vs lib/to_regexp.rb in to_regexp-0.1.2

- old
+ new

@@ -10,22 +10,35 @@ REGEXP_DELIMITERS = { '%r{' => '}', '/' => '/', } + # Get a regexp back + # + # Without :literal or :detect, `"foo".to_regexp` will return nil. + # + # @param [optional, Hash] options + # @option options [true,false] :literal Treat meta characters and other regexp codes as just text; always return a regexp + # @option options [true,false] :detect If string starts and ends with valid regexp delimiters, treat it as a regexp; otherwise, interpret it literally + # @option options [true,false] :ignore_case /foo/i + # @option options [true,false] :multiline /foo/m + # @option options [true,false] :extended /foo/x + # @option options [true,false] :lang /foo/[nesu] def to_regexp(options = {}) if args = as_regexp(options) ::Regexp.new *args end end - + + # Return arguments that can be passed to `Regexp.new` + # @see to_regexp def as_regexp(options = {}) unless options.is_a?(::Hash) raise ::ArgumentError, "[to_regexp] Options must be a Hash" end str = self.strip - - if options[:literal] == true + + if options[:literal] or (options[:detect] and REGEXP_DELIMITERS.none? { |k, v| str.start_with?(k) and str.end_with?(v) }) content = ::Regexp.escape str elsif delim_set = REGEXP_DELIMITERS.detect { |k, v| str.start_with?(k) } delim_start, delim_end = delim_set.map { |delim| ::Regexp.escape delim } /\A#{delim_start}(.*)#{delim_end}([^#{delim_end}]*)\z/u =~ str content = $1