Forked from hiasinho/factory_girl_strategy_find_or_create.rb
Created
February 7, 2019 04:28
-
-
Save LCShen/6c3e2e70f557f58b5696476aedb7fc81 to your computer and use it in GitHub Desktop.
FactoryGirl strategy for adding find & find_or_create
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## http://stackoverflow.com/questions/7145256 | |
| module FactoryGirl | |
| module Strategy | |
| class Find | |
| def association(runner) | |
| runner.run | |
| end | |
| def result(evaluation) | |
| build_class(evaluation).where(get_overrides(evaluation)).first | |
| end | |
| private | |
| def build_class(evaluation) | |
| evaluation.instance_variable_get(:@attribute_assigner).instance_variable_get(:@build_class) | |
| end | |
| def get_overrides(evaluation = nil) | |
| return @overrides unless @overrides.nil? | |
| evaluation.instance_variable_get(:@attribute_assigner).instance_variable_get(:@evaluator).instance_variable_get(:@overrides).clone | |
| end | |
| end | |
| class FindOrCreate | |
| def initialize | |
| @strategy = FactoryGirl.strategy_by_name(:find).new | |
| end | |
| delegate :association, to: :@strategy | |
| def result(evaluation) | |
| found_object = @strategy.result(evaluation) | |
| if found_object.nil? | |
| @strategy = FactoryGirl.strategy_by_name(:create).new | |
| @strategy.result(evaluation) | |
| else | |
| found_object | |
| end | |
| end | |
| end | |
| end | |
| register_strategy(:find, Strategy::Find) | |
| register_strategy(:find_or_create, Strategy::FindOrCreate) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment