Class: Crossroads::Router

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

Instance Method Summary collapse

Constructor Details

#initialize(dir) ⇒ Router

Returns a new instance of Router.



3
4
5
6
7
8
9
10
11
# File 'lib/crossroads/router.rb', line 3

def initialize(dir)
  raise "Cannot find routers directory #{dir}" unless File.directory?(dir)

  @routesdir = dir
  @triggerfile = File.join(@routesdir, "reload.txt")
  @checktime = 0

  loadroutes
end

Instance Method Details

#loadroute(route) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/crossroads/router.rb', line 47

def loadroute(route)
  route_name = File.basename(route, ".route")

  r = Route.new(route_name)
  r.load_route(route)

  @routes << r
rescue Exception => e
  STDERR.puts "Failed to load route #{route}"
  @routers.delete route_name rescue nil
end

#loadroutesObject



59
60
61
62
63
64
65
66
67
# File 'lib/crossroads/router.rb', line 59

def loadroutes
  @routes = []

  routefiles.each do |route|
    loadroute route
  end

  @loadtime = Time.now
end

#reload_routesObject



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/crossroads/router.rb', line 13

def reload_routes
  if (Time.now - @checktime).to_i > 30
    if File.exist?(@triggerfile)
      triggermtime = File::Stat.new(@triggerfile).mtime
      if triggermtime > @loadtime
        loadroutes
      end
    end

    @checktime = Time.now
  end
end

#route(msg) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/crossroads/router.rb', line 26

def route(msg)
  reload_routes

  targets = []

  @routes.each do |r|
    begin
      targets.concat(r.route!(msg))
    rescue
    end
  end

  targets
end

#routefilesObject



41
42
43
44
45
# File 'lib/crossroads/router.rb', line 41

def routefiles
  Dir.entries(@routesdir).grep(/\.route$/).map do |f|
    File.join([@routesdir, f])
  end.sort
end