Sha256: 20c2983c958346253c674361e623e8836e3b26aeb94405e64fe911b55f8650e6

Contents?: true

Size: 1.15 KB

Versions: 4

Compression:

Stored size: 1.15 KB

Contents

module Pieces
  class RouteCompiler
    attr_reader :path
    attr_reader :globals

    def initialize(config)
      @path = config[:path] || Dir.pwd
      @globals = config[:globals] || {}
    end

    def compile(files, name, route)
      files.merge("#{name}.html" => { contents: yield_pieces(route), type: 'html' })
    end

    private

    def piece_path(piece)
      Dir["#{path}/app/views/{#{piece},#{piece}/#{piece},application/#{piece}}.html.*"].first
    end

    def route_globals(route)
      globals.merge(route['_global'] || {})
    end

    def merge_globals(data, route)
      data.merge('_global' => route_globals(route).merge(data['_global'] || {}))
    end

    def pieces(data)
      (data['_pieces'] || []).map do |piece|
        [piece.keys.first, merge_globals(piece.values.first, data)]
      end
    end

    def compile_piece(piece, data)
      view_model = OpenStruct.new(data['_global'].merge(data))
      ::Tilt.new(piece_path(piece)).render(view_model) { yield_pieces(data) }
    end

    def yield_pieces(data)
      pieces(data).reduce('') do |contents, (piece, data)|
        contents << compile_piece(piece, data)
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
pieces-0.3.8 lib/pieces/compilers/route_compiler.rb
pieces-0.3.7 lib/pieces/compilers/route_compiler.rb
pieces-0.3.6 lib/pieces/compilers/route_compiler.rb
pieces-0.3.5 lib/pieces/compilers/route_compiler.rb