After being inspired by errtheblog’s sexy migrations ( Sexy Migrations — err.the_blog) I got tired of writing
my
un-sexy migrations containing line after line of remove_column and its
alter-ego add_column.
So I made two new methods, add_columns and remove_columns.
After being inspired by errtheblog’s sexy migrations ( Sexy Migrations — err.the_blog) I got tired of writing
my
un-sexy migrations containing line after line of remove_column and its
alter-ego add_column.
So I made two new methods, add_columns and remove_columns.
I think this is pretty neat. I like remove_columns especially. I
don’t know how much I’d really use add_columns, but having it like
that would be nice just in case.
I like it but I am surprised no one has ever made a syntax for adding
and removing columns that matches create table. To me, the following
would be ideal:
add_columns “users” do |t|
t.integer :group_id, :employer_id
t.string :first, :last
t.timestamps
end
remove_columns “users” do |t|
t.integer :group_id, :employer_id
t.string :first, :last
t.timestamps
end
Frankly this would be the most intuitive and should be part of the rails
core migrations system.
I probably won’t take the time to code this up but in case someone else
here is eager to do this, I can easily show you where to start. The
funny thing is that it would actually be ridiculously easy.
Here is the (abridged for relevance) code for “create_table”:
def create_table(table_name, options = {})
instantiate a “TableDefinition” class
table_definition = TableDefinition.new(self)
#…set the tables “id”…
#…
yield the instance to the user (let them make calls to the object)
yield table_definition
#make the sql based on the columns added to the instance
create_sql = #… turn the table_definition into SQL #run the sql that was built based on the columns stored in the
instance
execute create_sql
end
This is actually not very complicated at all. Simply “yielding” to the
code passed into the block so:
create_table “examples” do |t|
t.column :example, :integer
end
simply calls the “column” function on the “t” variable which is actually
an instance of TableDefinition
So, what is TableDefinition?
Just a class with some basic functions that adds columns to an instance
variable array and has a method for turning the columns array into sql.
That is basically the jist of it. I leave actually coding it as an
exercise to the reader, but I guarantee that it is doable.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.