msgbartop
Just a little about development! Think before you write!
msgbarbottom

28 Apr 08 Lazy men’s rails plugin - mydry

I have been using this little plugin I wrote for some time now.

The main idea is that I always start working in the migrations, and there I define: not null fields, length for string fields, what fields are numbers and what are not, references to other models (this at least can be guessed with the _id ending), unique fields or field groups and things like that.

After the migration is executed, I need to rewrite almost it all, with even more information in the model, for example: the maximum length for a string field is not enough anymore, now you need the minimum length too.

And I really do not like idea of doing the same thing more than once (I think some of you agree with me, even if you do not agree with my solution).

To solve this problem, I created this little plugin, that is really a generator

You want to see some code? So, let’s start with a migration: ./script/generate migration example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Example < ActiveRecord::Migration
  def self.up
    create_table :examples do |t|
      t.string :name, :null =&gt; false
      t.text :description
      t.integer :a_number
      t.references :example
    end
  end
 
  def self.down
    drop_table :examples
  end
end

Now, let’s run rake db:migrate && ./script/generate drymodel example
And it will generate the following code for the model:

1
2
3
4
5
6
7
8
9
class Example < ActiveRecord::Base
  #Relationships
  belongs_to :example
  #Validations
  validates_presence_of :name
  validates_numericality_of :a_number, :allow_nil =&gt; true
  validates_length_of :name, :maximum =&gt; 255, :allow_nil =&gt; true
  validates_associated :example, :allow_nil =&gt; true
end

Up to now, it generates validations for uniques, non nulls, numerics, associations, …
pretty much, every thing that you have already wrote on the migration.
Liked it?

to install, just add the github gem source (you need to do it only once):
gem sources -a http://gems.github.com/

and to install the plugin gem:
gem install urubatan-mydry_generator

Now you are ready to play!
If you want to take a look at the code, it is hosted in GitHub.
There is also a dryscaffold generator, that will do the same as the standard scaffold (with REST and all), but it list the columns from the database and you do not need to name them on the command line.
But I do not think it is that useful :D

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , , , , , ,