Sha256: 43031352a0fb86d2c7a39468f33f37ffc59a3951c681c3e8148ea26fee12c276

Contents?: true

Size: 1.82 KB

Versions: 3

Compression:

Stored size: 1.82 KB

Contents

require 'rails/generators/migration'
require 'rails/generators/generated_attribute'

module Stager
  class ModelGenerator < Rails::Generators::Base
    include Rails::Generators::Migration
    no_tasks { attr_accessor :model_name, :model_attributes }
    
    source_root File.expand_path('../templates', __FILE__)
    argument :model_name, :type => :string, :required => true
    argument :model_args, :type => :array, :default => []
    
    class_option :skip_migration, :type => :boolean, :default => false
    class_option :skip_timestamps, :type => :boolean, :default => false
    
    def set_options
      @model_attributes = []
      
      model_args.each do |arg|
        @model_attributes << Rails::Generators::GeneratedAttribute.new(*arg.split(':'))
      end
    end
    
    def create_model
      template 'model.rb', "app/models/#{model_path}.rb"
        
      template "spec/model.rb", "spec/models/#{model_path}_spec.rb"
      template 'spec/fixtures.yml', "spec/fixtures/#{model_path.pluralize}.yml"
    end
    
    def create_migration
      unless options[:skip_migration]
        migration_template 'migration.rb', "db/migrate/create_#{model_path.pluralize.gsub('/', '_')}.rb"
      end
    end
    
  private
    
    def model_path
      class_name.underscore
    end
    
    def table_name
      plural_name.gsub('/', '_')
    end
    
    def singular_name
      model_name.underscore
    end
    
    def plural_name
      model_name.underscore.pluralize
    end
    
    def class_name
      singular_name.camelize
    end
    
    def plural_class_name
      plural_name.camelize
    end
    
    def self.next_migration_number(dirname)
      if ActiveRecord::Base.timestamped_migrations
        Time.now.utc.strftime("%Y%m%d%H%M%S")
      else
        "%.3d" % (current_migration_number(dirname) + 1)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
stager-0.2.2 lib/generators/stager/model/model_generator.rb
stager-0.2.1 lib/generators/stager/model/model_generator.rb
stager-0.2.0 lib/generators/stager/model/model_generator.rb