Class: Observr::Controller

Inherits:
Object
  • Object
show all
Defined in:
lib/observr/controller.rb

Overview

The controller contains the app’s core logic.

Examples:


script = Observr::Script.new(file)
contrl = Observr::Controller.new(script, Observr.handler.new)
contrl.run

# Calling `run` will enter the listening loop, and from then on every
# file event will trigger its corresponding action defined in `script`

# The controller also automatically adds the script's file to its list of
# monitored files and will detect any changes to it, providing on the fly
# updates of defined rules.

Instance Method Summary collapse

Constructor Details

#initialize(script, handler) ⇒ Controller

Create a controller object around given ‘script`

Parameters:

See Also:



31
32
33
34
35
36
# File 'lib/observr/controller.rb', line 31

def initialize(script, handler)
  @script, @handler = script, handler
  @handler.add_observer(self)

  Observr.debug "using %s handler" % handler.class.name
end

Instance Method Details

#monitored_pathsArray<Pathname>

List of paths the script is monitoring.

Basically this means all paths below current directoly recursivelly that match any of the rules’ patterns, plus the script file.

Returns:

  • (Array<Pathname>)

    list of all monitored paths



78
79
80
81
82
83
84
# File 'lib/observr/controller.rb', line 78

def monitored_paths
  paths = Dir['**/*'].select do |path|
    @script.patterns.any? {|p| path.match(p) }
  end
  paths.push(@script.path).compact!
  paths.map {|path| Pathname(path).expand_path }
end

#runObject

Enter listening loop. Will block control flow until application is explicitly stopped/killed.



40
41
42
43
44
# File 'lib/observr/controller.rb', line 40

def run
  @script.parse!
  @handler.listen(monitored_paths)
rescue Interrupt
end

#update(path, event_type = nil) ⇒ Object

Callback for file events

Called while control flow is in listening loop. It will execute the file’s corresponding action as defined in the script. If the file is the script itself, it will refresh its state to account for potential changes.

Parameters:

  • path (Pathname, String)

    path that triggered the event

  • event (Symbol)

    event type



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/observr/controller.rb', line 58

def update(path, event_type = nil)
  path = Pathname(path).expand_path

  Observr.debug("received #{event_type.inspect} event for #{path.relative_path_from(Pathname(Dir.pwd))}")
  if path == @script.path && event_type != :accessed
    @script.parse!
    @handler.refresh(monitored_paths)
  else
    @script.action_for(path, event_type).call
  end
end