Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,35 @@ UserImport.new(file: csv_file) do
end
```

### Store metadata on the column description

You may find yourself wanting to store arbitrary metadata about a column.

For example, you may want to pull the schema for the importer dynamically and list out the
supported fields along with a description, to help guide users through an import
process on valid content.

This can be accomplished using the metadata Hash.

```ruby
class ImportUserCSV
model User

column :active, to: ->(value) { %w(y yes true active).include?(value.downcase) }, meta: { description: %q{Indicate if active using "Y", "yes", "true", "active" or just "no"} }

# optionally use I18n
column :active, to: ->(value) {}, meta: { description: I18n.t('my.custom.scope.active') }
end
```

To access this information and potentially display to users before uploading a
file to import:

```ruby
ImportUserCSV.config.column_definitions.each do |column|
puts "#{ column.name.to_s.titleize } - #{ column.metadata[:description] }"
end
```

### Validate the header

Expand Down
4 changes: 4 additions & 0 deletions lib/csv_importer/column_definition.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ module CSVImporter
# # email will be downcased
# column :email, to: ->(email) { email.downcase }
#
# # column defined with metadata
# column :active, meta: { description: %q{Can provide "Y", "Yes", "true" or simply "no"} }
#
# # transform `confirmed` to `confirmed_at`
# column :confirmed, to: ->(confirmed, model) do
# model.confirmed_at = confirmed == "true" ? Time.new(2012) : nil
Expand All @@ -30,6 +33,7 @@ class ColumnDefinition
attribute :to # Symbol or Proc
attribute :as # Symbol, String, Regexp, Array
attribute :required, Boolean
attribute :meta, Hash, default: {}

# The model attribute that this column targets
def attribute
Expand Down
18 changes: 18 additions & 0 deletions spec/csv_importer/column_definition_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,24 @@

module CSVImporter
describe ColumnDefinition do
describe '.meta' do
it 'defaults to an empty Hash' do
expect(subject.meta).to eq(Hash.new)
end

it 'does not transform values' do
subject.meta[:key] = 19.0

expect(subject.meta[:key]).to eq(19.0)
end

it 'does not transform keys' do
subject.meta['key'] = 19.0

expect(subject.meta[:key]).to eq(nil)
end
end

describe "#match?" do

matcher :match do |name|
Expand Down