Sha256: 36ce1c607a38f13297ecd099cc33605ad6bd37d090602b3738f4fa0ae3d5113a

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.3 lib/pieces/compilers/route_compiler.rb
pieces-0.3.2 lib/pieces/compilers/route_compiler.rb
pieces-0.3.1 lib/pieces/compilers/route_compiler.rb
pieces-0.3.0 lib/pieces/compilers/route_compiler.rb