Skip to content

Making Command Classes DRY

mosop edited this page Dec 11, 2016 · 5 revisions

Crystal CLI supports inheritance for command classes.

Class Inheritance

abstract class Face < Cli::Command
  class Options
    arg "face"
  end
end

class Hello < Face
  def run
    puts "hello #{args.face}"
  end
end

class Bye < Face
  def run
    puts "bye #{args.face}"
  end
end

Hello.run [":)"] # prints hello :)
Bye.run [":("] # prints bye :(

Module Including/Extending

module CongigFile
  macro included
    class Options
      string "-c", default: "./config.yml" 
    end

    @config : YAML::Any?
    def config
      @config ||= YAML.parse(File.expand_path(options.c))
    end
  end
end

class ReadConfig < Cli::Supercommand
  class Name < Cli::Command
    include ConfigFile

    def run
      puts config["name"]
    end
  end

  class Version < Cli::Command
    include ConfigFile

    def run
      puts config["version"]
    end
  end
end

Clone this wiki locally