Sha256: 48fc8c784c941691b4011f9f0c97df1962fe618b68cbd90fe9a954a169a3795f

Contents?: true

Size: 1.79 KB

Versions: 1

Compression:

Stored size: 1.79 KB

Contents

require 'rails/generators'
require "factory_girl_rails"
require 'generators/factory_girl/model/model_generator'

module FactoryFactoryGirl
  module Generators
    class ModelGenerator < FactoryGirl::Generators::ModelGenerator
      SKIPED_COLUMN = %w{id created_at updated_at}

      private

      def factory_attributes
        class_name.constantize.columns.map do |attribute|
          unless SKIPED_COLUMN.include? attribute.name
            "#{attribute.name} #{set_column(attribute)}"
          end
        end.compact.join("\n")
      end

      def set_column(attribute)
        match_results = rules.map do |rule|
          if attribute.name.match(rule[:rule])
            rule
          end
        end.compact

        if applied_rule = match_results.first
          if applied_rule[:value]
            transfer_value_type(applied_rule[:value], attribute.type.to_s)
          else
            "{ #{applied_rule[:function]} }"
          end
        else
          default_value(attribute)
        end
      end

      def transfer_value_type(value, type)
        case type
        when "string" || "text"
          "\"#{value}\""
        when "integer"
          value.to_i
        else
          value
        end
      end

      def default_value(attribute)
        if attribute.default
          attribute.default
        else
          case attribute.type.to_s
          when "string"
            "\"MyString\""
          when "integer"
            1
          when "text"
            "\"MyText\""
          when "boolean"
            true
          when "datetime"
            "\"#{Time.now}\""
          else
            nil
          end
        end
      end

      def rules
        if @rules
          @rules
        else
          FactoryFactoryGirl.configuration.rules
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
factory_factory_girl-0.1.5 lib/factory_factory_girl/generators/model_generator.rb