Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Let context be merged into import data #27

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
23 changes: 21 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,14 +177,15 @@ csv(csv_string, **options)
|Argument|Description|
|--------|-----------|
|`csv_string`|Data in the form of a CSV string.|
|`**options`|A hash of options. Available options are `headers:` and `attributes:`|
|`**options`|A hash of options. Available options are `headers:`, `attributes:`, and `context:`|

#### Options

|Option|Description|
|------|-----------|
|`headers:`|The CSV headers. Use when the supplied CSV string does not have headers.|
|`attributes:`|The attributes the headers should map to. Useful if the headers do not match the model's attributes.|
|`context:`|A hash of hard-coded data that is imported in addition to the import data. This can be used to make association validations pass if an import is meant to be scoped to a specific user or account, for example.|

##### Rolling back if a record fails to save

Expand Down Expand Up @@ -222,7 +223,25 @@ result = ArtVandelay::Import.new(:users).csv(csv_string, attributes: {email_addr
# => #<ArtVandelay::Import::Result>
```

##### Stripping whitespace
#### Adding context to imports

`ArtVandelay::Import#csv` supports a `:context` keyword argument. This lets you provide additional context that the import data may not contain. For example, you may wish to import all records with references to a specific user or account.

```ruby
csv_string = CSV.generate do |csv|
csv << ["email_address", "passcode"]
csv << ["george@vandelay_industries.com", "bosco"]
end

result = ArtVandelay::Import.new(:users).csv(
csv_string,
attributes: {email_address: :email, passcode: :password},
context: {account: Account.find_by!(code: "VANDELAY_INDUSTRIES")}
)
# => #<ArtVandelay::Import::Result>
```

#### Stripping whitespace

```ruby
csv_string = CSV.generate do |csv|
Expand Down
9 changes: 5 additions & 4 deletions lib/art_vandelay.rb
Original file line number Diff line number Diff line change
Expand Up @@ -150,16 +150,17 @@ def csv(csv_string, **options)
options = options.symbolize_keys
headers = options[:headers] || true
attributes = options[:attributes] || {}
context = options[:context] || {}
rows = build_csv(csv_string, headers)

if rollback
# TODO: It would be nice to still return a result object during a
# failure
active_record.transaction do
parse_rows(rows, attributes, raise_on_error: true)
parse_rows(rows, attributes, context, raise_on_error: true)
end
else
parse_rows(rows, attributes)
parse_rows(rows, attributes, context)
end
end

Expand Down Expand Up @@ -191,13 +192,13 @@ def build_params(row, attributes)
end
end

def parse_rows(rows, attributes, **options)
def parse_rows(rows, attributes, context, **options)
options = options.symbolize_keys
raise_on_error = options[:raise_on_error] || false
result = Result.new(rows_accepted: [], rows_rejected: [])

rows.each do |row|
params = build_params(row, attributes)
params = build_params(row, attributes).merge(context)
record = active_record.new(params)

if raise_on_error ? record.save! : record.save
Expand Down
27 changes: 27 additions & 0 deletions test/art_vandelay_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,33 @@ class Import < ArtVandelayTest
assert_equal "s3kure!", user_2.password
end

test "it accepts seeded Active Record attribute values" do
author_of_imported_posts =
User.create!(email: "[email protected]", password: "password")

csv_string = CSV.generate do |csv|
csv << %w[title1 content1]
csv << %w[title2 content2]
end

assert_difference("Post.count", 2) do
ArtVandelay::Import.new(:posts, rollback: true)
.csv(
csv_string,
headers: [:title, :content],
context: {user: author_of_imported_posts}
)
end

post_1 = Post.find_by!(title: "title1")
post_2 = Post.find_by!(title: "title2")

assert_equal "title1", post_1.title
assert_equal author_of_imported_posts, post_1.user
assert_equal "title2", post_2.title
assert_equal author_of_imported_posts, post_2.user
end

test "maps to custom headers" do
csv_string = CSV.generate do |csv|
csv << %w[email_address passcode]
Expand Down
3 changes: 3 additions & 0 deletions test/dummy/app/models/post.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class Post < ApplicationRecord
belongs_to :user
end
2 changes: 2 additions & 0 deletions test/dummy/app/models/user.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
class User < ApplicationRecord
validates :password, presence: true

has_many :posts
end
12 changes: 12 additions & 0 deletions test/dummy/db/migrate/20240324192541_create_posts.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class CreatePosts < ActiveRecord::Migration["#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}"]
def change
create_table :posts do |t|
t.string :title
t.string :content, null: false

t.references :user, null: false

t.timestamps
end
end
end
10 changes: 9 additions & 1 deletion test/dummy/db/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,15 @@
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 2022_10_08_115344) do
ActiveRecord::Schema[7.0].define(version: 2024_03_24_192541) do
create_table "posts", force: :cascade do |t|
t.string "title"
t.string "content", null: false
t.integer "user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_posts_on_user_id"
end

create_table "users", force: :cascade do |t|
t.string "email", null: false
Expand Down