Skip to content

Making Command Classes DRY

mosop edited this page Jan 28, 2017 · 5 revisions

Crystal CLI supports inheritance for command classes.

Class Inheritance

abstract class Say < Cli::Command
  class Options
    arg "message"
  end
end

class Smile < Say
  def run
    puts "#{args.message} :)"
  end
end

class Frown < Say
  def run
    puts "#{args.message} :("
  end
end

Smile.run %w(hello) # prints hello :)
Frown.run %w(bye) # 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.read(File.expand_path(options.c)))
    end
  end
end

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

    def run
      puts config["name"].as_s
    end
  end

  class Version < Cli::Command
    include ConfigFile

    def run
      puts config["version"].as_s
    end
  end
end
You can’t perform that action at this time.