Sha256: cc850e63a103fe27bdff238a71c881d28764e715d46d7ca820e5260542b0b659

Contents?: true

Size: 1.89 KB

Versions: 54

Compression:

Stored size: 1.89 KB

Contents

require 'hamlit'
require 'thor'

module Hamlit
  class CLI < Thor
    IGNORED_COMPILERS = ['HTML'].freeze

    desc 'render HAML', 'Render haml template'
    def render(file)
      code = generate_code(file)
      puts eval(code)
    end

    desc 'compile HAML', 'Show generated rendering code'
    def compile(file)
      code = generate_code(file)
      puts code
    end

    desc 'temple HAML', 'Show a compile result of hamlit AST'
    def temple(file)
      pp generate_temple_ast(file)
    end

    desc 'parse HAML', 'Show parse result'
    def parse(file)
      pp generate_hamlit_ast(file)
    end

    private

    # Flexible default_task, compatible with haml's CLI
    def method_missing(*args)
      return super(*args) if args.length > 1

      render(args.first.to_s)
    end

    def generate_code(file)
      template = File.read(file)
      Hamlit::Engine.new.call(template)
    end

    def generate_temple_ast(file)
      chain = Hamlit::Engine.chain.map(&:first).map(&:to_s)
      compilers = chain.select do |compiler|
        compiler =~ /\AHamlit::/ && !ignored_compilers.include?(compiler)
      end

      template = File.read(file)
      compilers.inject(template) do |exp, compiler|
        Module.const_get(compiler).new.call(exp)
      end
    end

    def generate_hamlit_ast(file)
      template = File.read(file)
      Hamlit::Parser.new.call(template)
    end

    # Enable colored pretty printing only for development environment.
    # I don't think it is a good idea to add pry as runtime dependency
    # just for debug color printing.
    def pp(arg)
      begin
        require 'pry'
        Pry::ColorPrinter.pp(arg)
      rescue LoadError
        require 'pp'
        super(arg)
      end
    end

    def ignored_compilers
      IGNORED_COMPILERS.map { |name| "Hamlit::#{name}" }
    end

    def symbolize_keys(hash)
      {}.tap { |h| hash.each { |k, v| h[k.to_sym] = v } }
    end
  end
end

Version data entries

54 entries across 54 versions & 1 rubygems

Version Path
hamlit-1.7.2 lib/hamlit/cli.rb
hamlit-1.7.1 lib/hamlit/cli.rb
hamlit-1.7.0 lib/hamlit/cli.rb
hamlit-1.6.7 lib/hamlit/cli.rb
hamlit-1.6.6 lib/hamlit/cli.rb
hamlit-1.6.5 lib/hamlit/cli.rb
hamlit-1.6.4 lib/hamlit/cli.rb
hamlit-1.6.3 lib/hamlit/cli.rb
hamlit-1.6.2 lib/hamlit/cli.rb
hamlit-1.6.1 lib/hamlit/cli.rb
hamlit-1.6.0 lib/hamlit/cli.rb
hamlit-1.5.9 lib/hamlit/cli.rb
hamlit-1.5.8 lib/hamlit/cli.rb
hamlit-1.5.7 lib/hamlit/cli.rb
hamlit-1.5.6 lib/hamlit/cli.rb
hamlit-1.5.5 lib/hamlit/cli.rb
hamlit-1.5.4 lib/hamlit/cli.rb
hamlit-1.5.3 lib/hamlit/cli.rb
hamlit-1.5.2 lib/hamlit/cli.rb
hamlit-1.5.1 lib/hamlit/cli.rb