Class: Exwiw::AfterInsertHook::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/exwiw/after_insert_hook.rb

Constant Summary collapse

COLLECTION_NAME_PATTERN =

Collection names become part of the output filename, so restrict them to plain path-safe names (no separators, no leading dot).

/\A[A-Za-z0-9_][A-Za-z0-9_.-]*\z/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cli_options, output_extension: nil) ⇒ Context

Returns a new instance of Context.



82
83
84
85
86
87
# File 'lib/exwiw/after_insert_hook.rb', line 82

def initialize(cli_options, output_extension: nil)
  @cli_options = cli_options
  @output_extension = output_extension
  @collected = []
  @collected_by_collection = {}
end

Instance Attribute Details

#cli_optionsObject (readonly)

Returns the value of attribute cli_options.



80
81
82
# File 'lib/exwiw/after_insert_hook.rb', line 80

def cli_options
  @cli_options
end

#collectedObject (readonly)

Returns the value of attribute collected.



80
81
82
# File 'lib/exwiw/after_insert_hook.rb', line 80

def collected
  @collected
end

#collected_by_collectionObject (readonly)

Returns the value of attribute collected_by_collection.



80
81
82
# File 'lib/exwiw/after_insert_hook.rb', line 80

def collected_by_collection
  @collected_by_collection
end

Instance Method Details

#insert_jsonl(collection_or_template, template = nil) ⇒ Object

With one argument, identical to insert_sql: the rendered output goes to the shared collection-less buffer (insert-NNN-after_insert.ext).

With two arguments (MongoDB adapter only), the rendered output is appended to the named collection's own buffer and written to insert-NNN-.jsonl. SQL statements name their table in-band, but JSONL documents do not — the import convention derives the target collection from the filename — so this is the only way a hook can seed documents into a specific collection.



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/exwiw/after_insert_hook.rb', line 102

def insert_jsonl(collection_or_template, template = nil)
  return insert_sql(collection_or_template) if template.nil?

  unless @output_extension == 'jsonl'
    raise ArgumentError,
          "insert_jsonl(collection, template) is only supported for the MongoDB adapter; " \
          "SQL statements already name their table, use insert_sql(template) instead."
  end

  collection = collection_or_template.to_s
  unless collection.match?(COLLECTION_NAME_PATTERN)
    raise ArgumentError, "invalid collection name for insert_jsonl: #{collection_or_template.inspect}"
  end

  (@collected_by_collection[collection] ||= []) << render(template)
end

#insert_sql(template) ⇒ Object



89
90
91
# File 'lib/exwiw/after_insert_hook.rb', line 89

def insert_sql(template)
  @collected << render(template)
end