Skip to content

Instantly share code, notes, and snippets.

@maunovaha
Forked from coorasse/fg_find_or_create.rb
Last active June 22, 2018 01:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save maunovaha/c9a32e217f5dab5d45a7055c69460e21 to your computer and use it in GitHub Desktop.
Save maunovaha/c9a32e217f5dab5d45a7055c69460e21 to your computer and use it in GitHub Desktop.
module FactoryGirl
module Syntax
module Methods
def find_or_create(name, *attributes, &block)
attributes = FactoryGirl.attributes_for(name, *attributes)
klass = FactoryGirl.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 || FactoryGirl.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