Importer DSL Idea
Jotting this down for feedback and for future reference.
# frozen_string_literal: true
module JekyllImport
class Foobar < Importers::Importer
title "Foo Bar"
needs "sequel", "sqlite3", "safe_yaml"
set_option "dbname", "--dbname DB", "Database name."
set_option "user", "--user NAME", "Database user name."
set_option "password", "--password PW", "Database user's password. (default: '')"
set_option "host", "--host HOST", "Database host name. (default: 'localhost')"
set_option "port", "--port NUM", "Database port. (default: '8080')"
class << self
# Entry point.
# Mandatory public method. Will raise exception if not defined.
def process(options)
# ...
end
# Optional public method
def validate(options)
# ...
end
private
# ...
end
end
end
I like this! It'd be really cool if we could mark the options as required inline instead of needing to do that in the validate func.
It'd be really cool if we could mark the options as required inline instead of needing to do that in the
validatefunc.
OptionParser itself doesn't have a builtin mechanism to enforce required options.
However, if given a Class for Type Coercion, it can throw error when passed an empty string. For example,
cmd.option "--export-file PATH", "Path to export file."
will not fail when --export-file is omitted or passed an empty string. But,
cmd.option "--export-file PATH", String, "Path to export file."
will fail when --export-file is passed an empty string. Omission is legal. (as of bundled version in Ruby 2.7.x).
Update: Just found out that we can define custom type coercion via OptionParser#accept 🎉