jekyll / jekyll-import

:inbox_tray: The "jekyll import" command for importing from various blogs to Jekyll format.
https://import.jekyllrb.com
MIT License
512 stars 315 forks source link

Importer DSL Idea #502

Open ashmaroli opened 1 year ago

ashmaroli commented 1 year ago

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
parkr commented 1 year ago

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.

ashmaroli commented 1 year ago

It'd be really cool if we could mark the options as required inline instead of needing to do that in the validate func.

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 🎉