Sha256: 0cd788d66a5b9fdc24459eb381d1226a6dfc6a2fc141173f227a96026060a18a

Contents?: true

Size: 1.83 KB

Versions: 5

Compression:

Stored size: 1.83 KB

Contents

require 'generators/factory_girl'
require 'factory_girl_rails'

module FactoryGirl
  module Generators
    class ModelGenerator < Base
      argument(
        :attributes,
        type: :array,
        default: [],
        banner: "field:type field:type"
      )

      class_option(
        :dir,
        type: :string,
        default: "test/factories",
        desc: "The directory or file root where factories belong"
      )

      def create_fixture_file
        if File.exist?(factories_file)
          insert_factory_into_existing_file
        else
          create_factory_file
        end
      end

      private

      def factories_file
        options[:dir] + ".rb"
      end

      def insert_factory_into_existing_file
        insert_into_file(
          factories_file,
          factory_definition,
          after: "FactoryGirl.define do"
        )
      end

      def create_factory_file
        filename = [table_name, filename_suffix].compact.join('_')
        file = File.join(options[:dir], "#{filename}.rb")
        create_file(file, single_file_factory_definition)
      end

      def factory_definition
<<-RUBY
  factory :#{singular_table_name}#{explicit_class_option} do
    #{factory_attributes}
  end
RUBY
      end

      def single_file_factory_definition
<<-RUBY
FactoryGirl.define do
#{factory_definition}
end
RUBY
      end

      def factory_attributes
        attributes.map do |attribute|
          "#{attribute.name} #{attribute.default.inspect}"
        end.join("\n")
      end

      def filename_suffix
        factory_girl_options[:suffix]
      end

      def factory_girl_options
        generators.options[:factory_girl] || {}
      end

      def generators
        config = FactoryGirl::Railtie.config
        config.respond_to?(:app_generators) ? config.app_generators : config.generators
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 3 rubygems

Version Path
sc_core-0.0.7 test/dummy/vendor/bundle/ruby/2.2.0/gems/factory_girl_rails-4.5.0/lib/generators/factory_girl/model/model_generator.rb
solidus_backend-1.0.0.pre3 vendor/bundle/gems/factory_girl_rails-4.5.0/lib/generators/factory_girl/model/model_generator.rb
solidus_backend-1.0.0.pre2 vendor/bundle/gems/factory_girl_rails-4.5.0/lib/generators/factory_girl/model/model_generator.rb
solidus_backend-1.0.0.pre vendor/bundle/gems/factory_girl_rails-4.5.0/lib/generators/factory_girl/model/model_generator.rb
factory_girl_rails-4.5.0 lib/generators/factory_girl/model/model_generator.rb