Sha256: 3e307f8099d72ebdd04b22fcc4fdc402b46e7ec1bf31504a060183c20faff81c

Contents?: true

Size: 1.57 KB

Versions: 6

Compression:

Stored size: 1.57 KB

Contents

class Stasis
  class Before < Plugin

    before_all :before_all
    before_render :before_render
    controller_method :before
    priority 1
    reset :reset

    def initialize(stasis)
      @stasis = stasis
      reset
    end

    # 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.
    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

    # 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`.
    def before_all
      new_paths = (@blocks || {}).keys.select do |path|
        path.is_a?(::String)
      end
      @stasis.paths = (@stasis.paths + new_paths).uniq
    end

    # 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.
    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

    # This event resets all instance variables.
    def reset
      @blocks = {}
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
stasis-0.2.0 lib/stasis/plugins/before.rb
stasis-0.2.0.pre lib/stasis/plugins/before.rb
stasis-0.1.23 lib/stasis/plugins/before.rb
stasis-0.1.22 lib/stasis/plugins/before.rb
stasis-0.1.21 lib/stasis/plugins/before.rb
stasis-0.1.20 lib/stasis/plugins/before.rb