How to create a migration file dynamically by meta programming in rails 4.0

If you want to create a migration file from a module written in lib file or somewhere from your ruby file and execute it, use the metaprogramming which can create a class or method dynamically. The following code snippet shows the methods we use and gives a better idea to create migration file dynamically.

def create_columns(tb_with_cols)
    add_columns = ""
    tb_name = tb_with_cols.keys.first
    columns = tb_with_cols.values.first
    columns.each { |c_name, c_type| add_columns << "\tadd_column(':#{tb_name}', :#{c_name}, :#{c_type})\n" }

    add_columns
 end

 def migration_file_content(tb_with_cols)
   cols = create_columns(tb_with_cols)
<<-RUBY
  class AddMissingColumnsToTable < ActiveRecord::Migration
     def change_table
    #{cols}
   end
 end
  RUBY
 end


 def write_content_to_file(path, content)
    File.open(path, 'w+') do |f|
      f.write(content)
    end
 end

Just call the method migration_file_content in your code. Pass the parameter tb_with_cols as a Hash, in which the key is the table_name and value is the columns that should be added to that table. Ex:

tb_with_cols = {:users => {:name => :string, :age => :integer, :address => :text} }
content = migration_file_content(tb_with_cols)
write_content_to_file("#{Rails.root}/db/migrations/', content)

After that call the method write_content_to_file with your new migration file path and the content from our migration_file_content method. 🙂

Advertisement

Author: Abhilash

I'm Abhilash, a web developer who specializes in Ruby development. With years of experience working with various frameworks like Rails, Angular, Sinatra, Laravel, NodeJS, React and more, I am passionate about building robust and scalable web applications. Since 2010, I have been honing my skills and expertise in the Ruby on Rails platform. This blog is dedicated to sharing my knowledge and experience on topics related to Ruby, Ruby on Rails, and other subjects that I have worked with throughout my career. Join me on this journey to explore the exciting world of web development!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: