Class: Stasis::Before

Inherits:
Plugin
  • Object
show all
Defined in:
lib/stasis/plugins/before.rb

Instance Method Summary collapse

Methods inherited from Plugin

#_match_key?, _priority, #_within?, inherited, plugins, priority

Constructor Details

#initialize(stasis) ⇒ Before

Returns a new instance of Before.



10
11
12
13
# File 'lib/stasis/plugins/before.rb', line 10

def initialize(stasis)
  @stasis = stasis
  reset
end

Instance Method Details

#before(*paths, &block) ⇒ Object

This method is bound to all controllers. Stores a block in the ‘@blocks` `Hash`, where the key is a path and the value is an `Array` of blocks.



17
18
19
20
21
22
23
24
25
26
# File 'lib/stasis/plugins/before.rb', line 17

def before(*paths, &block)
  paths = [ nil ] if paths.empty?
  if block
    paths.each do |path|
      path = @stasis.controller._resolve(path, true)
      @blocks[path] ||= []
      @blocks[path] << [ @stasis.path, block ]
    end
  end
end

#before_allObject

This event triggers before all files render. When a ‘before` call receives a path that does not exist, we want to create that file dynamically. This method adds those dynamic paths to the `paths` `Array`.



31
32
33
34
35
36
# File 'lib/stasis/plugins/before.rb', line 31

def before_all
  new_paths = (@blocks || {}).keys.select do |path|
    path.is_a?(::String)
  end
  @stasis.paths = (@stasis.paths + new_paths).uniq
end

#before_renderObject

This event triggers before each file renders through Stasis. It finds matching blocks for the ‘path` and evaluates those blocks using the `action` as a scope.



40
41
42
43
44
45
46
47
48
49
# File 'lib/stasis/plugins/before.rb', line 40

def before_render
  matches = _match_key?(@blocks, @stasis.path)
  matches.each do |group|
    group.each do |(path, block)|
      if _within?(path)
        @stasis.action.instance_eval(&block)
      end
    end
  end
end

#resetObject

This event resets all instance variables.



52
53
54
# File 'lib/stasis/plugins/before.rb', line 52

def reset
  @blocks = {}
end