lib/faker_maker/factory.rb in faker_maker-2.0.0 vs lib/faker_maker/factory.rb in faker_maker-2.1.1

- old
+ new

@@ -79,10 +79,11 @@ end def as_json(*_args) build.as_json end + alias to_h as_json def parent? !@parent.nil? end @@ -161,16 +162,32 @@ def value_for_attribute( instance, attr, attr_override_values ) if attribute_hash_overridden_value?( attr, attr_override_values ) attr_override_values[attr.name] elsif attr.array? - [].tap { |a| attr.cardinality.times { a << instance.instance_eval(&attr.block) } } + [].tap do |a| + attr.cardinality.times do + manufacture = manufacture_from_embedded_factory( attr ) + # if manufacture has been build and there is a block, instance_exec the block + # otherwise just add the manufacture to the array + a << (attr.block ? instance.instance_exec(manufacture, &attr.block) : manufacture) + end + end else - instance.instance_eval(&attr.block) + manufacture = manufacture_from_embedded_factory( attr ) + attr.block ? instance.instance_exec(manufacture, &attr.block) : manufacture end end + def manufacture_from_embedded_factory( attr ) + # The name of the embedded factory randomly selected from the list of embedded factories. + embedded_factory_name = attr.embedded_factories.sample + # The object that is being manufactured by the factory. + # If an embedded factory name is provided, it builds the object using FakerMaker. + embedded_factory_name ? FakerMaker[embedded_factory_name].build : nil + end + def instantiate assemble.new end def attach_attributes_to_class @@ -184,9 +201,10 @@ @klass.define_method :as_json do |options = {}| super( options.merge( except: 'fm_factory' ) ) .transform_keys { |key| @fm_factory.json_key_map[key] || key } .filter { |key, value| !@fm_factory.find_attribute(key)&.omit?( value ) } end + @klass.alias_method :to_h, :as_json end def assert_valid_options( options ) options.assert_valid_keys :class, :parent, :naming end