Module: Fabrial::Fabricate
- Included in:
- Fabrial
- Defined in:
- lib/fabrial/fabricate.rb
Overview
TODO: properly hook up parent associations for pre-created objects passed in
Instance Method Summary collapse
-
#add_default_return(objects) ⇒ Object
If a return object(s) wasn’t specified, default to returning the first object.
- #extract_child_records(klass, data) ⇒ Object
-
#fabricate(objects) ⇒ Object
Make expects a nested hash of type => data or [data].
Instance Method Details
#add_default_return(objects) ⇒ Object
If a return object(s) wasn’t specified, default to returning the first object. TODO: Raise error if mixing array and hash return styles
25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/fabrial/fabricate.rb', line 25 def add_default_return(objects) return if contains_return? objects ret = objects.values.find do |v| v.is_a?(Hash) || (v.is_a?(Array) && !v.empty?) end if ret ret = ret.first if ret.is_a? Array ret[:RETURN] = true end end |
#extract_child_records(klass, data) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/fabrial/fabricate.rb', line 37 def extract_child_records(klass, data) children = data.select do |type, v| # Must have nested data [Array, Hash].any? { |c| v.is_a? c } && # Must be a class that we can instantiate get_class(type) && # Even if it has the same name as a Model in the system, if it is also # the name of a column in the table, assume the data is for a serialzed # field and not a nested relation. Ex: Requests have a serialized field # called content and there is also a Content model in the system. ( # If they are using a class as the key, then always choose the class # over the field. type.is_a?(Class) || !column_names(klass).include?(type.to_s) ) end data.extract!(*children.keys) end |
#fabricate(objects) ⇒ Object
Make expects a nested hash of type => data or [data]
7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/fabrial/fabricate.rb', line 7 def fabricate(objects) objects = Fabrial.run_before_fabricate objects add_default_return objects ancestors = {} returns = make_types objects, ancestors # If returns is made up of pairs, return a hash. if returns.first.is_a? Array returns.to_h else returns.length <= 1 ? returns.first : returns end end |