public
Description: A less sucky way to do fixtures, sort of
Clone URL: git://github.com/pat-maddox/test_exemplars.git
auto id field

git-svn-id: svn://evang.eli.st/public/plugins/test_exemplars@1452 
82013aef-fb27-0410-99a1-c1893322ecab
pat (author)
Wed Aug 08 12:02:21 -0700 2007
commit  f94175090dc7559609e3c07276691dfbdead9346
tree    70cc25b46d26413c6e61b74ef056a24c0d687025
parent  78838cde48e569c9baa32328a891520f7dc7c79b
0
...
33
34
35
 
 
 
 
 
 
 
36
37
...
33
34
35
36
37
38
39
40
41
42
43
44
0
@@ -33,4 +33,11 @@ exemplify also takes an optional block. This is useful for methods you need to
0
   exemplify(Chicken) {|c| c.ssn = "abc123" }
0
   Chicken.exemplar => #<Chicken:0x3136e1c @attributes={"name"=>nil, "ssn"=>"abc123", "age"=>nil}, @new_record=true>
0
   
0
+Finally, you can automatically populate a field's value with an autoincrementing exemplar ID.
0
+
0
+ # auto populate name field
0
+ exemplify Chicken, :auto_id => :name
0
+ Chicken.exemplar => #<Chicken:0x311d638 @new_record=true, @attributes={"name"=>"Chicken1", "ssn"=>nil, "age"=>nil}>
0
+ Chicken.exemplar => #<Chicken:0x311d638 @new_record=true, @attributes={"name"=>"Chicken2", "ssn"=>nil, "age"=>nil}>
0
+
0
 You can also automatically save the record with ARClass.create_exemplar and ARClass.create_exemplar!. They're just convenience methods that build an exemplar and call #save and #save! respectively.
0
\ No newline at end of file
...
3
4
5
 
 
6
7
8
9
10
11
 
 
 
 
12
13
14
...
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
0
@@ -3,12 +3,18 @@ module ExemplarBuilder
0
     count_var_name = "@@#{klass.to_s.underscore}_exemplar_count"
0
     klass.send :class_variable_set, count_var_name, 0
0
     
0
+ @@auto_field = options.delete(:auto_id)
0
+
0
     (class << klass; self; end).class_eval do
0
       default_exemplar = klass.new options
0
       yield(default_exemplar) if block_given?
0
       
0
       define_method(:exemplar) do |*overrides|
0
         class_variable_set count_var_name, (class_variable_get(count_var_name) + 1)
0
+ if @@auto_field
0
+ default_exemplar.send "#{@@auto_field}=", "#{klass}#{class_variable_get(count_var_name)}"
0
+ end
0
+
0
         default_exemplar.attributes = *overrides
0
         default_exemplar
0
       end
...
47
48
49
 
 
 
 
 
 
50
51
...
47
48
49
50
51
52
53
54
55
56
57
0
@@ -47,4 +47,10 @@ describe ExemplarBuilder do
0
     exemplify Chicken, :name => "lame name"
0
     lambda { Chicken.create_exemplar! :name => "really lame" }.should raise_error
0
   end
0
+
0
+ it "should allow for automatically populating an attribute based on exemplar count" do
0
+ exemplify Chicken, :auto_id => :name
0
+ Chicken.exemplar.name.should == "Chicken1"
0
+ Chicken.exemplar.name.should == "Chicken2"
0
+ end
0
 end
0
\ No newline at end of file

Comments

    No one has commented yet.