Repository navigation
Customizing Bulkrax
This page is for developers changing how Bulkrax imports and exports: adjusting each row's metadata, parsing values with a custom matcher, adding Guided Import checks, and writing new parsers and entries. For settings that need no code, see Configuring Bulkrax. To understand the order things happen in, read how an import runs first.
On this page
- Changing each row's metadata (
add_local) - Custom matchers
- Custom Guided Import checks
- Overriding Bulkrax code
- Custom parsers and entries
- Extension points
The install generator writes app/models/concerns/bulkrax/has_local_processing.rb with an empty add_local method. Bulkrax calls it at the end of building each row's metadata, for CSV, OAI and RDF entries, after the row's values are in parsed_metadata (the attributes sent to the repository). Change parsed_metadata there:
# app/models/concerns/bulkrax/has_local_processing.rb
module Bulkrax
module HasLocalProcessing
def add_local
title = parsed_metadata['title']
parsed_metadata['title'] = Array(title).map { |t| "Digitized: #{t}" } if title.present?
end
end
endadd_local runs on every row, so keep it fast and leave rows it does not apply to unchanged.
A matcher turns one cell into the value or values stored in a field. It applies the mapping's options in this order:
- Returns nothing if the mapping is
excluded, or the field is reserved. - Applies
if:and returns nothing if the value does not match. In Bulkrax 10.0 an empty cell in a column withif:raises an error; give such columns a value or removeif:. - Collapses line breaks and tabs to spaces and trims the value.
- Splits it if the mapping has
split:. - Turns a single-item list back into a single value.
- If the mapping has
parsed: true, runs the matcher'sparse_<name>method on each value. A method that returnsnildrops that value.
Each entry class picks its matcher with self.matcher_class. Bulkrax::CsvEntry uses Bulkrax::CsvMatcher; other entries use Bulkrax::ApplicationMatcher.
A parse method runs only when all three are true:
- The matcher has a method named
parse_<name>. -
<name>is listed in the matcher'sparsed_fields. - The field's mapping has
parsed: true.
Missing any one of them, the value is stored as it is, without an error. For example, to normalize date_created values in CSV imports:
# config/initializers/bulkrax_matchers.rb
Rails.application.config.to_prepare do
Bulkrax::CsvMatcher.class_eval do
def parse_date_created(src)
Date.parse(src).iso8601
rescue ArgumentError
src # keep values that are not dates as they are
end
end
Bulkrax::CsvMatcher.parsed_fields += ['date_created'] unless Bulkrax::CsvMatcher.parsed_fields.include?('date_created')
end# Bulkrax initializer, or the tenant's field mappings in Hyku
config.field_mappings['Bulkrax::CsvParser']['date_created'] = { from: ['date_created'], parsed: true }Things to know:
-
parsed_fieldsis matched by substring: the first entry contained in the field name is used. Withdatein the list,date_createdwould callparse_date. Use full field names. - Columns without a mapping get
parsed: trueonly whenApplicationMatcher(notCsvMatcher) has the method. For a method added toCsvMatcher, add a mapping withparsed: true. - The built-in parse methods are
remote_files,language,subject,types,model,resource_typeandformat_original. Overriding one changes every import that parses that field.
A new entry can have its own matcher. Inherit from Bulkrax::ApplicationMatcher (or a subclass), add or override methods, and return the class from the entry's self.matcher_class.
Guided Import runs a list of checks on every row (config.csv_row_validators). Add your own with register_csv_row_validator:
module MyApp
module RequireYearInDate
def self.call(record, row_index, context)
date = record[:raw_row]['date_created']
return if date.blank? || date.match?(/\d{4}/)
context[:errors] << { row: row_index, source_identifier: record[:source_identifier],
severity: 'warning', category: 'date_without_year',
column: 'date_created', value: date,
message: "'#{date}' has no year." }
end
end
end
Bulkrax.setup do |config|
config.register_csv_row_validator(MyApp::RequireYearInDate)
endA check receives the row (record[:raw_row] holds the cells by header), its line number in the CSV (the first data row is 2), and a shared context. Add each problem to context[:errors], with severity: 'error' or severity: 'warning'; that is the list Guided Import reports. (context also has a :warnings key, but nothing reads it.) Register checks rather than replacing config.csv_row_validators, so checks added to Bulkrax later still run.
When add_local, a matcher or a setting is not enough, override Bulkrax classes in the application with a module prepended at load time (inside Rails.application.config.to_prepare), so the change survives code reloading. Keep overrides small and mark each changed method, so they can be checked when Bulkrax is upgraded.
Bulkrax comes with parsers for CSV, BagIt, XML and OAI. For a new format, write a parser (reads the source and creates one entry per record) and an entry (turns one record into metadata and builds the record). Common formats are welcome as contributions to Bulkrax.
For example app/models/bulkrax/foo_entry.rb, inheriting from Bulkrax::Entry or one of its subclasses (such as Bulkrax::CsvEntry).
For import, implement:
| Method | Purpose |
|---|---|
self.read_data(path) |
Read the metadata file. |
self.fields_from_data(data) |
The field names present in the data (used to build default mappings). |
self.data_for_entry(data, source_id, parser) |
The raw metadata for one record, stored on the entry. |
build_metadata |
Turn the raw metadata into parsed_metadata. Usually calls add_metadata for each field, then add_visibility, add_rights_statement, add_admin_set_id and add_local. |
record |
The record's raw data, as used by build_metadata. |
self.matcher_class (optional) |
The matcher to use; defaults to Bulkrax::ApplicationMatcher. |
self.parent_field(parser), self.child_field(parser) (optional) |
The fields holding relationships; default to the parser's relationship mappings. |
For export, implement build_export_metadata, which fills parsed_metadata from the repository record.
Collections and file sets usually get their own entry classes (for example FooCollectionEntry, FooFileSetEntry), returned by the parser.
For example app/parsers/bulkrax/foo_parser.rb, inheriting from Bulkrax::ApplicationParser or one of its subclasses.
| Method | Purpose |
|---|---|
entry_class, collection_entry_class, file_set_entry_class
|
The entry classes for each kind of record. Each raises NotImplementedError until defined. |
records(opts = {}) |
All records in the source. |
works, collections, file_sets
|
The records of each kind. create_objects calls these by name for each type it imports. |
works_total |
The number of works, for the importer's counts. Required: ApplicationParser does not define it. |
collections_total, file_sets_total
|
Optional; default 0. |
valid_import? |
Optional checks before any row runs; return false to stop the import. |
self.import_supported?, self.export_supported?
|
Optional; default true and false. |
setup_export_file, write_files
|
Required when export_supported? is true. |
create_collections, create_works, create_file_sets and create_relationships are provided; they call create_objects with one type each. A parser and its entries need not share a name: the BagIt parser uses CSV entries.
The importer form shows each parser's own fields from a partial, for example app/views/bulkrax/importers/_foo_fields.html.erb. Its outermost element must have a class matching the partial's name (<div class='foo_fields'>). A parser can reuse an existing partial. If a new partial does not appear when the parser is chosen, clear the application's cache (rm -rf tmp/cache/*) and reload.
Add the parser to config.parsers in the Bulkrax initializer, with its name, class and partial. See Configuring Bulkrax: Parsers.
| To change | Use |
|---|---|
| Each row's metadata |
add_local (above) |
| How cells become values | Field mapping options; custom matchers (above) |
| What Guided Import checks |
register_csv_row_validator (above) |
| How records are found, created, updated and deleted |
config.object_factory: a subclass of Bulkrax::ValkyrieObjectFactory, or a class implementing Bulkrax::ObjectFactoryInterface (Using Bulkrax without Hyrax) |
Which class a model value means |
config.factory_class_name_coercer (Configuring Bulkrax) |
| How parents and children are linked |
config.relationship_job_class: a job class replacing Bulkrax::CreateRelationshipsJob
|
| Blank values sent to the repository |
transformation_removes_blank_hash_values on the factory class |
| Who may import and export | The four methods from Bulkrax::AbilityBehavior (Installing and enabling Bulkrax) |
| What an export writes | Field mappings (join, generated, skip_object_for_model_names); build_export_metadata in a custom entry |
| New formats | Custom parsers and entries (above) |
| Interface text | Bulkrax's locale files (config/locales/bulkrax.*.yml); override keys in the application's own locale files |
Using Bulkrax
Importing
Changing imported records
Exporting
Configuring Bulkrax
- Installing and enabling
- Configuring Bulkrax
- Repository modes
- Common gotchas
- Using Bulkrax without Hyrax
Developing with Bulkrax
Upgrading
Getting help