Skip to content

Instantly share code, notes, and snippets.

@kjlape
Last active December 11, 2021 02:20
Show Gist options
  • Save kjlape/69150c8e0ba3d9b2ff25c03d7578a9db to your computer and use it in GitHub Desktop.
Save kjlape/69150c8e0ba3d9b2ff25c03d7578a9db to your computer and use it in GitHub Desktop.
module Seeders
class Base
def seed!(builder, findable_attributes, unstable_attributes = {})
builder.find_or_create_by!(findable_attributes) do |config|
config.assign_attributes(unstable_attributes)
end
end
end
class Builder
def method_missing(name, *params, &block)
matches = name.to_s.match(/(?<model>\w+)(?<bang>!)?(?<question>\?)?/)
model, bang, _question = matches.values_at(:model, :bang, :question)
plural = model.pluralize
if name == plural
name.classify.constantize
elsif bang.present?
if respond_to?(model)
send(model, *params).tap(&:save!)
else
send(plural).create!(params, &block)
end
else
send(plural).new(params, &block)
end
end
def respond_to_missing?(name, *)
name.classify.constantize
rescue NameError
false
end
end
end
builder = Builder.new
builder.widget # initializes a widget in memory
builder.widget! # creates a widget and saves it in the db
# …
class Builder < Seeders::Builder
def widgets
Widget.create_with(
name: "A Widget",
scrobbler: scrobbler
)
end
def scrobbler
Scrobbler.create_with(
description: "A Scrobbler"
)
end
def users
User.create_with(
first_name: "Bob",
last_name: "Smith",
email: "[email protected]",
password: "password"
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment