We can inject
arbitrary Ruby code into the YAML file above using ERb??™s <% %> and <%= %> tags,
including whatever logic we need:
<% User.find_all_by_active(true).each_with_index do |user, i| %>
<%= user.login %>_project:
id: <%= i %>
owner_id: <%= user.id %>
billing_status_id: <%= user.billing_status.id %>
<% end %>
ActiveRecord??™s implementation of this handy trick couldn??™t be simpler:
yaml = YAML::load(erb_render(yaml_string))
using the helper method erb_render:
def erb_render(fixture_content)
ERB.new(fixture_content).result
end
Generative programming often uses either Module#define_method or class_eval and
def to create methods on-the-fly. ActiveRecord uses this technique for attribute
accessors; the generate_read_methods feature defines the setter and reader methods
as instance methods on the ActiveRecord class in order to reduce the number of
times method_missing (a relatively expensive technique) is needed.
Continuations
Continuations are a very powerful control-flow mechanism. A continuation represents
a particular state of the call stack and lexical variables. It is a snapshot of a
point in time when evaluating Ruby code. Unfortunately, the Ruby 1.8 implementation
of continuations is so slow as to be unusable for many applications. The upcoming
Ruby 1.9 virtual machines may improve this situation, but you should not expect good
performance from continuations under Ruby 1.
Pages:
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54