CrudVision – Lisa Seelye

July 30, 2008

Fixtures in Rails Suck – this makes them suck less

Filed under: open source,rails,snippet,testing — Lisa Seelye @ 01:31

If you've got a boat load of legacy fixtures laying around (and who doesn't?) it can be a pain now that Rails handles the ID of objects so you don't have to.

On the train back from holiday I wrote a snippet of code to migrate them:

RUBY:
  1. def Util.real_yml(klass,col = 'name')
  2.     y = YAML.load_file(File.join(RAILS_ROOT,'test','fixtures',"#{klass.to_s.tableize}.yml"))
  3.     real_names = y.inject([]) { |names,(key,val)| names <<y[key][col] if y[key][col] ;names  }
  4.     real_objs = klass.find :all, :conditions => [ "#{col} IN (?)",real_names ], :o rder => "#{col} asc"
  5.     yml = ""
  6.     real_objs.each do |real_obj|
  7.       yml += "#{real_obj.name.downcase.gsub(' ','_').gsub('-','')}:\n"
  8.       real_obj.attributes.each do |k,v|
  9.         if k =~ /_id$/ && real_obj.respond_to?(k.gsub(/_id$/,'').to_sym) && ! v.nil?
  10.           n_klass = k.gsub(/_id$/,'').camelize.constantize.find(v) rescue nil
  11.           key = k.gsub(/_id$/,'')
  12.           val = n_klass.name.downcase.gsub(' ','_').gsub('-','')
  13.           yml += "  #{key}: #{val}\n"
  14.         else
  15.           yml += "  #{k}: #{v}\n" unless k.to_s == 'id'
  16.         end
  17.       end
  18.     end
  19.     yml
  20.   end

The use is:

RUBY:
  1. require 'util'
  2. print Util.real_yml(Corporation)

Copy/paste into corporations.yml

So far it's working great!

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress