lib/faker_maker/factory.rb in faker_maker-1.1.2 vs lib/faker_maker/factory.rb in faker_maker-1.1.3

- old
+ new

@@ -1,10 +1,12 @@ +# frozen_string_literal: true + # rubocop:disable Metrics/ClassLength module FakerMaker # Factories construct instances of a fake class Factory - attr_reader :name, :attributes, :class_name, :parent + attr_reader :name, :class_name, :parent def initialize( name, options = {} ) assert_valid_options options @name = name.respond_to?(:to_sym) ? name.to_sym : name.to_s.underscore.to_sym @class_name = (options[:class] || @name).to_s.camelcase @@ -45,10 +47,14 @@ def to_json(*_args) build.to_json end + def as_json(*_args) + build.as_json + end + def parent? !@parent.nil? end def json_key_map @@ -63,12 +69,21 @@ @json_key_map end def attribute_names( collection = [] ) collection |= FakerMaker[parent].attribute_names( collection ) if parent? - collection | attributes.map( &:name ) + collection | @attributes.map( &:name ) end + + def attributes( collection = [] ) + collection |= FakerMaker[parent].attributes( collection ) if parent? + collection | @attributes + end + + def find_attribute( name = '' ) + attributes.filter { |a| a.name == name }.first + end protected def populate_instance( instance, attr_override_values ) FakerMaker[parent].populate_instance instance, attr_override_values if parent? @@ -114,10 +129,12 @@ @klass.send( :attr_reader, :fm_factory ) end def attach_json_overrides_to_class @klass.define_method :as_json do |options = {}| - super( options.merge( except: 'fm_factory' ) ).transform_keys { |key| @fm_factory.json_key_map[key] || key } + 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 end def assert_valid_options( options ) options.assert_valid_keys :class, :parent