Ruby on Rails Custom Migration Generator

后端 未结 3 1108
走了就别回头了
走了就别回头了 2021-02-06 11:38

I\'m creating a Rails gem that integrates closely with Active Record. The gem requires a number of fields to be defined. For example:

class User < ActiveRecor         


        
3条回答
  •  走了就别回头了
    2021-02-06 12:24

    While Pravin did point in the right direction, i found it was not straightforward to implement it. I did the following, i added a file in config/initializers (name is not relevant), containing the following:

    require 'active_support'
    require 'active_record'
    
    class YourApplication
      module SchemaDefinitions
    
        module ExtraMethod
          def attachment(*args)
            options = args.extract_options!
            args.each do |col|
              column("#{col}_identifier", :string, options)
              column("#{col}_extension", :string, options)
              column("#{col}_size", :integer, options)
            end
          end
        end
    
        def self.load!
          ::ActiveRecord::ConnectionAdapters::TableDefinition.class_eval { include YourApplication::SchemaDefinitions::ExtraMethod }
        end
    
      end
    end
    
    
    ActiveSupport.on_load :active_record do
      YourApplication::SchemaDefinitions.load!
    end
    

    then you can just do something like:

    rails g model Person name:string title:string avatar:attachment
    

    which will create the following migration:

    def self.up
      create_table :people do |t|
        t.string :name
        t.string :title
        t.attachment :avatar
    
        t.timestamps
      end
    end
    

    If you then run the migration, rake db:migrate it will create the following Person model:

    ruby-1.9.2-p0 > Person
     => Person(id: integer, name: string, title: string, avatar_identifier: string, avatar_extension: string, avatar_size: integer, created_at: datetime, updated_at: datetime) 
    

    Hope this helps!!

提交回复
热议问题