21
Feb
08

Create Structured Data in Migrations

Occassionally I’ll decide to create some structured data in a migration by issuing create statements against my model classes. In a project I’m currently working on, I had to do this several levels deep. Rather than using temporary variables to create the sub items and so-on, all in a lexically flat structure, I came up with this simple one-liner:

def self.with(o); yield o; end

Doing this now allows me to issue those creates with nested data as a series of nested blocks, which is looks much better. For example:

with ChordQuality.create(:name => 'Major', :code => 'MAJ') do |q|
  with q.chords.create(:name => 'Major Triad') do |c|
    c.chord_symbols.create(:name => 'maj')
    c.chord_symbols.create(:name => 'M', :case_sensitive => true)
  end
  with q.chords.create(:name => 'Major 7') do |c|
    c.chord_symbols.create(:name => 'maj7')
    c.chord_symbols.create(:name => 'M7', :case_sensitive => true)
    with c.children.create(:name => 'Major 7 #11') do |cc|
      cc.chord_symbols.create(:name => 'maj7#11')
      cc.chord_symbols.create(:name => 'M7#11')
      cc.chord_symbols.create(:name => 'lyd')
      cc.chord_symbols.create(:name => 'lydian')
    end
  end

  with q.chords.create(:name => 'Major 6') do |c|
    c.chord_symbols.create(:name => 'maj6')
    c.chord_symbols.create(:name => 'M6', :case_sensitive => true)
  end
end

Oh, the beauty of Ruby code blocks!


0 Responses to “Create Structured Data in Migrations”


  1. No Comments

  • Ben Hughes

    I'm a freelance developer working with Ruby and other modern tools to build web applications, based currently out of Rochester, NY. I love to learn about new technologies and am always trying to achieve elegance and beauty through code.

    When I'm not writing software, I like to play tennis, dabble in jazz piano, and ponder economics. I'm a big fan of: world travel and cultures, jazz music, Korean food, coffee, and having interesting conversations.

  • Recommend Me
February 2008
M T W T F S S
« Jan   Mar »
 123
45678910
11121314151617
18192021222324
2526272829