Skip to content

Instantly share code, notes, and snippets.

@genericsteele
Last active August 29, 2015 13:57
Show Gist options
  • Save genericsteele/9514299 to your computer and use it in GitHub Desktop.
Save genericsteele/9514299 to your computer and use it in GitHub Desktop.
Fixture label interpolation

Fixtures and $LABELs

Currently, fixtures can interpolate labels has values like so:

eric:
  name: $LABEL
  email: eric@iamericsteele.com

This is helpful, but I think it could be improved with additional substring interpolation like this:

eric:
  name: $LABEL
  last_name: Steele
  email: $LABEL@iamericsteele.com

Clearly, I'm not saving myself any work with this example, but if we combine it with defaults, it makes things a bit easier.

DEFAULTS: &DEFAULTS
  name: $LABEL
  email: $LABEL@testmail.com
  bio: "I am $LABEL's medulla oblongata"
  role: user
  encrypted_password: <%= User.new.send(:password_digest, 'mellon') %>
  
eric:
  <<: *DEFAULTS
  
mark:
  <<: *DEFAULTS

admin:
  <<: *DEFAULTS
  name: sue
  role: admin
  
<% 1.upto(5) do |i| %>
number_<%= i %>:
  <<: *DEFAULTS
  bio: "$LABEL is alive"
  
<% end %>

Would end up being

eric:
  name: eric
  email: eric@testmail.com
  bio: "I am eric's medulla oblongata"
  role: user
  encrypted_password: <%= User.new.send(:password_digest, 'mellon') %>
  
mark:
  name: mark
  email: mark@testmail.com
  bio: "I am mark's medulla oblongata"
  role: user
  encrypted_password: <%= User.new.send(:password_digest, 'mellon') %>

admin:
  name: sue
  email: admin@testmail.com
  bio: "I am admin's medulla oblongata"
  role: admin
  encrypted_password: <%= User.new.send(:password_digest, 'mellon') %>
  
number_1:
  name: number_1
  email: number_1@testmail.com
  bio: "number_1 is alive"
  role: user
  encrypted_password: <%= User.new.send(:password_digest, 'mellon') %>
  
number_2:
  name: number_2
  email: number_2@testmail.com
  bio: "number_2 is alive"
  role: user
  encrypted_password: <%= User.new.send(:password_digest, 'mellon') %>
  
number_3:
  name: number_3
  email: number_3@testmail.com
  bio: "number_3 is alive"
  role: user
  encrypted_password: <%= User.new.send(:password_digest, 'mellon') %>
  
number_4:
  name: number_4
  email: number_4@testmail.com
  bio: "number_4 is alive"
  role: user
  encrypted_password: <%= User.new.send(:password_digest, 'mellon') %>
  
number_5:
  name: number_5
  email: number_5@testmail.com
  bio: "number_5 is alive"
  role: user
  encrypted_password: <%= User.new.send(:password_digest, 'mellon') %>

Yeah, yaml defaults are bit ugly, but I think this would make them and $LABELs more useable. The question is, should I write a patch to activerecord/lib/active_record/fixtures.rb that would change this functionality?

@magicmarkker
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment