Skip to content

Instantly share code, notes, and snippets.

@sunny
Last active January 12, 2022 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunny/94cf5613fd968d1d4cc725c9d9374990 to your computer and use it in GitHub Desktop.
Save sunny/94cf5613fd968d1d4cc725c9d9374990 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
class Blog::ArticlePlanter < Planter
def check(slug_en:)
Blog::Article.where(slug_en: slug_en).any?
end
def create(params)
FactoryBot.create(:blog_article, params)
end
end
12.times do |index|
Blog::ArticlePlanter.plant(slug_en: "lorem-#{index}") do
{
blog_category: Blog::Category.by_random.first
}
end
end
# frozen_string_literal: true
class Planter
# Override this method.
# Use the given arguments to find a record and return a truthy value if found.
#
# Example:
# class UserPlanter < Planter
# def check(email:)
# User.where(email: email).any?
# end
#
# # …
# end
def check(**query)
raise NotImplementedError
end
# Override this method.
# Use the given arguments to create a record.
#
# Example:
# class UserPlanter < Planter
# # …
#
# def create(**params)
# User.create(**params)
# end
# end
def create(**params)
raise NotImplementedError
end
# Call this method in your seed file for each instance you want to create.
#
# Will not create a record if another record is found with the same params.
#
# Example:
# Planter.plant(email: "alice@example.com")
# Planter.plant(email: "bob@example.com")
#
# For extra parameters that are not used to find the record, pass them inside
# a block. Both query and block parameters will be merged when calling create.
#
# Example:
# UserPlanter.plant(email: "alice@example.com") do
# {
# first_name: "Alice",
# height: [20, 160, 4_550].sample,
# }
# end
def self.plant(**params, &block)
new(**params).plant(&block)
end
def initialize(**query)
@query = query
end
def plant(**params)
if check(query)
print "."
return
end
puts
puts "#{name} #{pretty_query}"
block_params = block_given? ? yield : {}
create(**query, **params, **block_params)
rescue ActiveRecord::RecordNotUnique => e
warn e.message
end
private
attr_reader :query
def name
self.class.name.delete_suffix("Planter")
end
def pretty_query
query.map { |k, v| "#{k}: #{v.inspect}" }.join(" ")
end
end
require "factory_bot_rails"
require "faker"
require_relative "planter"
require_relative "seeds/blog_article_seeds"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment