Skip to content

Instantly share code, notes, and snippets.

@shockby
Forked from maunovaha/fg_find_or_create.rb
Last active June 22, 2018 01:46
Show Gist options
  • Save shockby/b2ec21d4410fcf7ca8cc43348e7d9165 to your computer and use it in GitHub Desktop.
Save shockby/b2ec21d4410fcf7ca8cc43348e7d9165 to your computer and use it in GitHub Desktop.
module FactoryBot
module Syntax
module Methods
def find_or_create(name, *attributes, &block)
attributes = FactoryBot.attributes_for(name, *attributes)
klass = FactoryBot.factory_by_name(name).build_class
enums = klass.defined_enums
find_attributes = attributes.clone
find_attributes.keys.each do |key|
find_attributes[key] = enums[key.to_s][find_attributes[key]] if enums.has_key?(key.to_s)
end
result = klass.find_by(find_attributes, &block)
result || FactoryBot.create(name, attributes, &block)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment