File: to_pattern.rb

package info (click to toggle)
ruby-mustermann19 0.4.3%2Bgit20160621-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 756 kB
  • ctags: 445
  • sloc: ruby: 7,197; makefile: 3
file content (50 lines) | stat: -rw-r--r-- 1,475 bytes parent folder | download
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
require 'mustermann'

module Mustermann
  # Mixin for adding {#to_pattern} ducktyping to objects.
  #
  # @example
  #   require 'mustermann/to_pattern'
  #
  #   class Foo
  #     include Mustermann::ToPattern
  #
  #     def to_s
  #       ":foo/:bar"
  #     end
  #   end
  #
  #   Foo.new.to_pattern # => #<Mustermann::Sinatra:":foo/:bar">
  #
  # By default included into String, Symbol, Regexp, Array and {Mustermann::Pattern}.
  module ToPattern
    PRIMITIVES = [String, Symbol, Array, Regexp, Mustermann::Pattern]
    #private_constant :PRIMITIVES

    # Converts the object into a {Mustermann::Pattern}.
    #
    # @example converting a string
    #   ":name.png".to_pattern # => #<Mustermann::Sinatra:":name.png">
    #
    # @example converting a string with options
    #   "/*path".to_pattern(type: :rails) # => #<Mustermann::Rails:"/*path">
    #
    # @example converting a regexp
    #   /.*/.to_pattern # => #<Mustermann::Regular:".*">
    #
    # @example converting a pattern
    #   Mustermann.new("foo").to_pattern # => #<Mustermann::Sinatra:"foo">
    #
    # @param [Hash] options The options hash.
    # @return [Mustermann::Pattern] pattern corresponding to object.
    def to_pattern(options = {})
      input   = self if PRIMITIVES.any? { |p| self.is_a? p }
      input ||= __getobj__ if respond_to?(:__getobj__)
      Mustermann.new(input || to_s, options)
    end

    PRIMITIVES.each do |klass|
      append_features(klass)
    end
  end
end