I’ve been mulling over an idea for a bit of new syntax, want to hear what you think about it.
Two of the most common things I do as a developer when generating a new migration are (1) add defaults to help avoid nil errors and (2) add indices to attributes like foreign keys for performance. The migration generator comes with nice syntax that makes adding indices easy:
But there’s no corresponding syntax for adding defaults. You generate the migration, find the generated file, add defaults by hand and then run the migration. What about a way to add defaults to new migrations from the command line? Could look like this:
rails g migration AddGearsToBicycles gears:integer[default:3]
``
Or in a new model:
rails g model Bicycle mileage:integer[default:0] gears:integer[default:3]
``
Improvements or suggestions on the proposed syntax? Any feedback would be much appreciated! Thanks everyone.
Sounds good. Keep in mind that you could potentially be dealing with dynamic values (such as Date, Time, and co) and also binary data, ltrees, and so on. Ideally you want to cover all these types, which is prehaps why this was not done in the first place.
Hi, I actually have this on my projects, I still need to make it public, but I was trying to make it more stable first.
The main idea was to be able to add anything inside the brackets, so you could include anything valid as options. The main problem is to use spaces or quotes.
rails g migration AddGearsToBicycles gears:integer[default:3,limit:10,null:false]
``
In my version, I also create the models (when models are created) using the validations for each parameter, when applicable.
Ill try to create an public repo for that in a day or two.
@Everton – cool! Yeah, I think it’s a fairly common problem.
I out started with a similar syntax to yours, but I found that writing out “default: …” every time got cumbersome. Since it’s a command line generator, the terser the syntax can be the better. In the end I liked a = character the best to indicate the default. Of the alternatives, : was more complicated to parse, > evoked the “:default =>” syntax nicely but did strange things with the output, so = seemed like a nice, terse, clear option.