Skip to content

Commit

Permalink
Add decorative section method. (#74)
Browse files Browse the repository at this point in the history
Sometimes people try to sub-divide a file with comments to connote sections,
but my eye always end up skipping those. And you can't nest them with more indentation.

Instead we can add a decorative method to help us — and we can use blocks to help indent
certain sections.
  • Loading branch information
kaspth authored Jan 7, 2024
1 parent 1937605 commit 4439288
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
23 changes: 23 additions & 0 deletions lib/oaken/seeds.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,29 @@ def seed(*directories)
ensure
@loader = nil
end

# `section` is purely for decorative purposes to carve up `Oaken.prepare` and seed files.
#
# Oaken.prepare do
# section :roots # Just the very few top-level models like Accounts and Users.
# users.defaults email_address: -> { Faker::Internet.email }, webauthn_id: -> { SecureRandom.hex }
#
# section :stems # Models building on the roots.
#
# section :leafs # Remaining models, bulk of them, hanging off root and stem models.
#
# section do
# seed :accounts, :data
# end
# end
#
# Since `section` is defined as `def section(*, **) = yield if block_given?`, you can use
# all of Ruby's method signature flexibility to help communicate structure better.
#
# Use positional and keyword arguments, or use blocks to indent them, or combine them all.
def section(*, **)
yield if block_given?
end
end

# Call `seed` in tests to load individual case files:
Expand Down
9 changes: 8 additions & 1 deletion test/dummy/db/seeds.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
Oaken.prepare do
section :registrations
register Menu::Item

section :roots
user_counter = 0
users.defaults name: -> { "Customer #{user_counter += 1}" }

seed :accounts, :data
section :stems
section :leafs

section do
seed :accounts, :data
end
end
4 changes: 4 additions & 0 deletions test/dummy/db/seeds/accounts/kaspers_donuts.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
section :accounts
donuts = accounts.create :kaspers_donuts, name: "Kasper's Donuts"

section :users
kasper = users.create :kasper, name: "Kasper", accounts: [donuts]
coworker = users.create :coworker, name: "Coworker", accounts: [donuts]

section :menus, :with_items
menu = menus.create account: donuts
plain_donut = menu_items.create menu: menu, name: "Plain", price_cents: 10_00
sprinkled_donut = menu_items.create menu: menu, name: "Sprinkled", price_cents: 10_10

section :orders
supporter = users.create name: "Super Supporter"
orders.insert_all [user_id: supporter.id, item_id: plain_donut.id] * 10

Expand Down

0 comments on commit 4439288

Please sign in to comment.