Class: Urifetch::Router

Inherits:
Object
  • Object
show all
Defined in:
lib/urifetch/router.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}, &block) ⇒ Router

Returns a new instance of Router.



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/urifetch/router.rb', line 7

def initialize(options={},&block)
  
  options = default_options = {
    strategy_key:    "base",
    class_name:   "Urifetch::Strategy::Base"
  }.merge(options)
  
  @routes = Hash.new(options)
  
  instance_eval(&block) if block_given?
  
  @routes[/(?<base>(?<match_id>.*))/i] = @routes[""]
end

Instance Attribute Details

#routesObject (readonly)

Returns the value of attribute routes.



5
6
7
# File 'lib/urifetch/router.rb', line 5

def routes
  @routes
end

Instance Method Details

#find(uri) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/urifetch/router.rb', line 21

def find(uri)
  
  # Tries to find a match
  match_data = @routes.keys.map{|r|r.match(uri.to_s)}.reject{|r|r.nil?}[0]
  
  # Fetches route data for given regex
  route_data = @routes[match_data.regexp]
        
  begin
    # Spawns strategy instance by constantizing strategy name
    class_name = route_data[:strategy_class] || "Urifetch::Strategy::" + route_data[:strategy_key].classify
    strategy = class_name.constantize.new(uri,match_data,route_data)
    
  rescue NameError
    # Spawns base strategy instance
    strategy = Strategy::Base.new(uri,match_data,route_data)
  end
  
  return strategy
  
end