This repository has been archived by the owner on Jan 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
generators.html
884 lines (814 loc) · 40.3 KB
/
generators.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Ruby on Rails Guides: Creating and Customizing Rails Generators & Templates</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
<a href="http://rubyonrails.org/">Overview</a> |
<a href="http://rubyonrails.org/download">Download</a> |
<a href="http://rubyonrails.org/deploy">Deploy</a> |
<a href="http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/overview">Code</a> |
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
<a href="http://rubyonrails.org/documentation">Documentation</a> |
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
<a href="http://rubyonrails.org/community">Community</a> |
<a href="http://weblog.rubyonrails.org/">Blog</a>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
<ul class="nav">
<li><a href="index.html">홈</a></li>
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">목차</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<dl class="L">
<dt>시작</dt>
<dd><a href="getting_started.html">레일즈 시작하기</a></dd>
<dt>모델(Models)</dt>
<dd><a href="migrations.html">레일즈 데이터베이스 마이그레이션</a></dd>
<dd><a href="active_record_validations_callbacks.html">액티브 레코드 데이터 검증(Validation)과 Callback(콜백)</a></dd>
<dd><a href="association_basics.html">액티브 레코드 Association(관계)</a></dd>
<dd><a href="active_record_querying.html">액티브 레코드 쿼리 인터페이스</a></dd>
<dt>뷰(Views)</dt>
<dd><a href="layouts_and_rendering.html">레이아웃(Layouts)과 렌더링(Rendering)</a></dd>
<dd><a href="form_helpers.html">액션 뷰 폼 핼퍼(Action View Form Helpers)</a></dd>
<dt>컨트롤러(Controllers)</dt>
<dd><a href="action_controller_overview.html">액션 컨트롤러 둘러보기</a></dd>
<dd><a href="routing.html">외부 요청에 대한 레일즈 라우팅</a></dd>
</dl>
<dl class="R">
<dt>심화내용</dt>
<dd><a href="active_support_core_extensions.html">액티브 서포트(Active Support) 확장(Core Extensions)</a></dd>
<dd><a href="i18n.html">레일즈 국제화I(nternationalization) API</a></dd>
<dd><a href="action_mailer_basics.html">액션 메일러의 기본</a></dd>
<dd><a href="testing.html">레일즈 어플리케이션 테스트하기</a></dd>
<dd><a href="security.html">레일즈 어플리케이션의 보안</a></dd>
<dd><a href="debugging_rails_applications.html">레일즈 어플리케이션 디버깅</a></dd>
<dd><a href="performance_testing.html">레일즈 어플리케이션 성능 테스트하기</a></dd>
<dd><a href="configuring.html">레일즈 어플리케이션 설정</a></dd>
<dd><a href="command_line.html">레일즈 커멘드라인 도구와 Rake 테스크</a></dd>
<dd><a href="caching_with_rails.html">레일즈를 이용한 캐싱</a></dd>
<dt>레일즈 확장하기(Extending Rails)</dt>
<dd><a href="plugins.html">레일즈 플러그인 작성의 기본</a></dd>
<dd><a href="rails_on_rack.html">렉 위의 레일즈(Rails on Rack)</a></dd>
<dd><a href="generators.html">레일즈 제너레이터(Generator) 제작과 수정</a></dd>
<dt>루비 온 레이즈에 기여하기</dt>
<dd><a href="contributing_to_ruby_on_rails.html">루비 온 레이즈에 기여하기</a></dd>
<dd><a href="api_documentation_guidelines.html">API 문서 가이드라인</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">루비 온 레일즈 가이드에 대한 가이드라인</a></dd>
<dt>Release Notes</dt>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
</dl>
</div>
</li>
<li><a href="contribute.html">기여하기</a></li>
<li><a href="credits.html">수고하신 분들</a></li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Creating and Customizing Rails Generators & Templates</h2>
<p>Rails generators are an essential tool if you plan to improve your workflow. With this guide you will learn how to create generators and customize existing ones.</p>
<p>In this guide you will:</p>
<ul>
<li>Learn how to see which generators are available in your application</li>
<li>Create a generator using templates</li>
<li>Learn how Rails searches for generators before invoking them</li>
<li>Customize your scaffold by creating new generators</li>
<li>Customize your scaffold by changing generator templates</li>
<li>Learn how to use fallbacks to avoid overwriting a huge set of generators</li>
<li>Learn how to create an application template</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#first-contact">First Contact</a></li><li><a href="#creating-your-first-generator">Creating Your First Generator</a></li><li><a href="#creating-generators-with-generators">Creating Generators with Generators</a></li><li><a href="#generators-lookup">Generators Lookup</a></li><li><a href="#customizing-your-workflow">Customizing Your Workflow</a></li><li><a href="#customizing-your-workflow-by-changing-generators-templates">Customizing Your Workflow by Changing Generators Templates</a></li><li><a href="#adding-generators-fallbacks">Adding Generators Fallbacks</a></li><li><a href="#application-templates">Application templates</a></li><li><a href="#generator-methods">Generator methods</a><ul><li><a href="#plugin"><tt>plugin</tt></a></li> <li><a href="#gem"><tt>gem</tt></a></li> <li><a href="#add_source"><tt>add_source</tt></a></li> <li><a href="#application"><tt>application</tt></a></li> <li><a href="#git"><tt>git</tt></a></li> <li><a href="#vendor"><tt>vendor</tt></a></li> <li><a href="#lib"><tt>lib</tt></a></li> <li><a href="#rakefile"><tt>rakefile</tt></a></li> <li><a href="#initializer"><tt>initializer</tt></a></li> <li><a href="#generate"><tt>generate</tt></a></li> <li><a href="#rake"><tt>rake</tt></a></li> <li><a href="#capify"><tt>capify!</tt></a></li> <li><a href="#route"><tt>route</tt></a></li> <li><a href="#readme"><tt>readme</tt></a></li></ul></li><li><a href="#changelog">Changelog</a></li></ol></div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<div class='note'><p>This guide is about generators in Rails 3, previous versions are not covered.</p></div>
<h3 id="first-contact">1 First Contact</h3>
<p>When you create an application using the <tt>rails</tt> command, you are in fact using a Rails generator. After that, you can get a list of all available generators by just invoking <tt>rails generate</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails new myapp
$ cd myapp
$ rails generate
</pre>
</div>
</notextile>
<p>You will get a list of all generators that comes with Rails. If you need a detailed description of the helper generator, for example, you can simply do:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate helper --help
</pre>
</div>
</notextile>
<h3 id="creating-your-first-generator">2 Creating Your First Generator</h3>
<p>Since Rails 3.0, generators are built on top of <a href="http://github.com/wycats/thor">Thor</a>. Thor provides powerful options parsing and a great <span class="caps">API</span> for manipulating files. For instance, let’s build a generator that creates an initializer file named <tt>initializer.rb</tt> inside <tt>config/initializers</tt>.</p>
<p>The first step is to create a file at <tt>lib/generators/initializer_generator.rb</tt> with the following content:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class InitializerGenerator < Rails::Generators::Base
def create_initializer_file
create_file "config/initializers/initializer.rb", "# Add initialization content here"
end
end
</pre>
</div>
</notextile>
<div class='note'><p><tt>create_file</tt> is a method provided by <tt>Thor::Actions</tt> and the documentation for it and its brethren can be found at <a href="http://rdoc.info/github/wycats/thor/master/Thor/Actions">rdoc.info</a>.</p></div>
<p>Our new generator is quite simple: it inherits from <tt>Rails::Generators::Base</tt> and has one method definition. Each public method in the generator is executed when a generator is invoked. Finally, we invoke the <tt>create_file</tt> method that will create a file at the given destination with the given content. If you are familiar with the Rails Application Templates <span class="caps">API</span>, you’ll feel right at home with the new generators <span class="caps">API</span>.</p>
<p>To invoke our new generator, we just need to do:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate initializer
</pre>
</div>
</notextile>
<p>Before we go on, let’s see our brand new generator description:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate initializer --help
</pre>
</div>
</notextile>
<p>Rails is usually able to generate good descriptions if a generator is namespaced, as <tt>ActiveRecord::Generators::ModelGenerator</tt>, but not in this particular case. We can solve this problem in two ways. The first one is calling <tt>desc</tt> inside our generator:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class InitializerGenerator < Rails::Generators::Base
desc "This generator creates an initializer file at config/initializers"
def create_initializer_file
create_file "config/initializers/initializer.rb", "# Add initialization content here"
end
end
</pre>
</div>
</notextile>
<p>Now we can see the new description by invoking <tt>--help</tt> on the new generator. The second way to add a description is by creating a file named <tt>USAGE</tt> in the same directory as our generator. We are going to do that in the next step.</p>
<h3 id="creating-generators-with-generators">3 Creating Generators with Generators</h3>
<p>Generators themselves have a generator:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate generator initializer
create lib/generators/initializer
create lib/generators/initializer/initializer_generator.rb
create lib/generators/initializer/USAGE
create lib/generators/initializer/templates
</pre>
</div>
</notextile>
<p>This is the generator just created:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class InitializerGenerator < Rails::Generators::NamedBase
source_root File.expand_path("../templates", __FILE__)
end
</pre>
</div>
</notextile>
<p>First, notice that we are inheriting from <tt>Rails::Generators::NamedBase</tt> instead of <tt>Rails::Generators::Base</tt>. This means that our generator expects at least one argument, which will be the name of the initializer, and will be available in our code in the variable <tt>name</tt>.</p>
<p>We can see that by invoking the description of this new generator (don’t forget to delete the old generator file):</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate initializer --help
Usage:
rails generate initializer NAME [options]
</pre>
</div>
</notextile>
<p>We can also see that our new generator has a class method called <tt>source_root</tt>. This method points to where our generator templates will be placed, if any, and by default it points to the created directory <tt>lib/generators/initializer/templates</tt>.</p>
<p>In order to understand what a generator template means, let’s create the file <tt>lib/generators/initializer/templates/initializer.rb</tt> with the following content:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Add initialization content here
</pre>
</div>
</notextile>
<p>And now let’s change the generator to copy this template when invoked:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class InitializerGenerator < Rails::Generators::NamedBase
source_root File.expand_path("../templates", __FILE__)
def copy_initializer_file
copy_file "initializer.rb", "config/initializers/#{file_name}.rb"
end
end
</pre>
</div>
</notextile>
<p>And let’s execute our generator:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate initializer core_extensions
</pre>
</div>
</notextile>
<p>We can see that now a initializer named core_extensions was created at <tt>config/initializers/core_extensions.rb</tt> with the contents of our template. That means that <tt>copy_file</tt> copied a file in our source root to the destination path we gave. The method <tt>file_name</tt> is automatically created when we inherit from <tt>Rails::Generators::NamedBase</tt>.</p>
<p>The methods that are available for generators are covered in the <a href="#generator-methods">final section</a> of this guide.</p>
<h3 id="generators-lookup">4 Generators Lookup</h3>
<p>When you run <tt>rails generate initializer core_extensions</tt> Rails requires these files in turn until one is found:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
rails/generators/initializer/initializer_generator.rb
generators/initializer/initializer_generator.rb
rails/generators/initializer_generator.rb
generators/initializer_generator.rb
</pre>
</div>
</notextile>
<p>If none is found you get an error message.</p>
<div class='info'><p>The examples above put files under the application’s <tt>lib</tt> because said directory belongs to <tt>$LOAD_PATH</tt>.</p></div>
<h3 id="customizing-your-workflow">5 Customizing Your Workflow</h3>
<p>Rails own generators are flexible enough to let you customize scaffolding. They can be configured in <tt>config/application.rb</tt>, these are some defaults:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.generators do |g|
g.orm :active_record
g.template_engine :erb
g.test_framework :test_unit, :fixture => true
end
</pre>
</div>
</notextile>
<p>Before we customize our workflow, let’s first see what our scaffold looks like:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate scaffold User name:string
invoke active_record
create db/migrate/20091120125558_create_users.rb
create app/models/user.rb
invoke test_unit
create test/unit/user_test.rb
create test/fixtures/users.yml
route resources :users
invoke scaffold_controller
create app/controllers/users_controller.rb
invoke erb
create app/views/users
create app/views/users/index.html.erb
create app/views/users/edit.html.erb
create app/views/users/show.html.erb
create app/views/users/new.html.erb
create app/views/users/_form.html.erb
invoke test_unit
create test/functional/users_controller_test.rb
invoke helper
create app/helpers/users_helper.rb
invoke test_unit
create test/unit/helpers/users_helper_test.rb
invoke stylesheets
create public/stylesheets/scaffold.css
</pre>
</div>
</notextile>
<p>Looking at this output, it’s easy to understand how generators work in Rails 3.0 and above. The scaffold generator doesn’t actually generate anything, it just invokes others to do the work. This allows us to add/replace/remove any of those invocations. For instance, the scaffold generator invokes the scaffold_controller generator, which invokes erb, test_unit and helper generators. Since each generator has a single responsibility, they are easy to reuse, avoiding code duplication.</p>
<p>Our first customization on the workflow will be to stop generating stylesheets and test fixtures for scaffolds. We can achieve that by changing our configuration to the following:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.generators do |g|
g.orm :active_record
g.template_engine :erb
g.test_framework :test_unit, :fixture => false
g.stylesheets false
end
</pre>
</div>
</notextile>
<p>If we generate another resource with the scaffold generator, we can see that neither stylesheets nor fixtures are created anymore. If you want to customize it further, for example to use DataMapper and RSpec instead of Active Record and TestUnit, it’s just a matter of adding their gems to your application and configuring your generators.</p>
<p>To demonstrate this, we are going to create a new helper generator that simply adds some instance variable readers. First, we create a generator within the rails namespace, as this is where rails searches for generators used as hooks:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate generator rails/my_helper
</pre>
</div>
</notextile>
<p>After that, we can delete both the <tt>templates</tt> directory and the <tt>source_root</tt> class method from our new generators, because we are not going to need them. So our new generator looks like the following:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Rails::MyHelperGenerator < Rails::Generators::NamedBase
def create_helper_file
create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
module #{class_name}Helper
attr_reader :#{plural_name}, :#{plural_name.singularize}
end
FILE
end
end
</pre>
</div>
</notextile>
<p>We can try out our new generator by creating a helper for users:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate my_helper products
</pre>
</div>
</notextile>
<p>And it will generate the following helper file in <tt>app/helpers</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module ProductsHelper
attr_reader :products, :product
end
</pre>
</div>
</notextile>
<p>Which is what we expected. We can now tell scaffold to use our new helper generator by editing <tt>config/application.rb</tt> once again:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.generators do |g|
g.orm :active_record
g.template_engine :erb
g.test_framework :test_unit, :fixture => false
g.stylesheets false
g.helper :my_helper
end
</pre>
</div>
</notextile>
<p>and see it in action when invoking the generator:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate scaffold Post body:text
[...]
invoke my_helper
create app/helpers/posts_helper.rb
</pre>
</div>
</notextile>
<p>We can notice on the output that our new helper was invoked instead of the Rails default. However one thing is missing, which is tests for our new generator and to do that, we are going to reuse old helpers test generators.</p>
<p>Since Rails 3.0, this is easy to do due to the hooks concept. Our new helper does not need to be focused in one specific test framework, it can simply provide a hook and a test framework just needs to implement this hook in order to be compatible.</p>
<p>To do that, we can change the generator this way:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Rails::MyHelperGenerator < Rails::Generators::NamedBase
def create_helper_file
create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
module #{class_name}Helper
attr_reader :#{plural_name}, :#{plural_name.singularize}
end
FILE
end
hook_for :test_framework
end
</pre>
</div>
</notextile>
<p>Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both <tt>Rails::TestUnitGenerator</tt> and <tt>TestUnit::MyHelperGenerator</tt>. Since none of those are defined, we can tell our generator to invoke <tt>TestUnit::Generators::HelperGenerator</tt> instead, which is defined since it’s a Rails generator. To do that, we just need to add:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Search for :helper instead of :my_helper
hook_for :test_framework, :as => :helper
</pre>
</div>
</notextile>
<p>And now you can re-run scaffold for another resource and see it generating tests as well!</p>
<h3 id="customizing-your-workflow-by-changing-generators-templates">6 Customizing Your Workflow by Changing Generators Templates</h3>
<p>In the step above we simply wanted to add a line to the generated helper, without adding any extra functionality. There is a simpler way to do that, and it’s by replacing the templates of already existing generators, in that case <tt>Rails::Generators::HelperGenerator</tt>.</p>
<p>In Rails 3.0 and above, generators don’t just look in the source root for templates, they also search for templates in other paths. And one of them is <tt>lib/templates</tt>. Since we want to customize <tt>Rails::Generators::HelperGenerator</tt>, we can do that by simply making a template copy inside <tt>lib/templates/rails/helper</tt> with the name <tt>helper.rb</tt>. So let’s create that file with the following content:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
module <%= class_name %>Helper
attr_reader :<%= plural_name %>, <%= plural_name.singularize %>
end
</pre>
</div>
</notextile>
<p>and revert the last change in <tt>config/application.rb</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.generators do |g|
g.orm :active_record
g.template_engine :erb
g.test_framework :test_unit, :fixture => false
g.stylesheets false
end
</pre>
</div>
</notextile>
<p>If you generate another resource, you can see that we get exactly the same result! This is useful if you want to customize your scaffold templates and/or layout by just creating <tt>edit.html.erb</tt>, <tt>index.html.erb</tt> and so on inside <tt>lib/templates/erb/scaffold</tt>.</p>
<h3 id="adding-generators-fallbacks">7 Adding Generators Fallbacks</h3>
<p>One last feature about generators which is quite useful for plugin generators is fallbacks. For example, imagine that you want to add a feature on top of TestUnit like <a href="http://github.com/thoughtbot/shoulda">shoulda</a> does. Since TestUnit already implements all generators required by Rails and shoulda just wants to overwrite part of it, there is no need for shoulda to reimplement some generators again, it can simply tell Rails to use a <tt>TestUnit</tt> generator if none was found under the <tt>Shoulda</tt> namespace.</p>
<p>We can easily simulate this behavior by changing our <tt>config/application.rb</tt> once again:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.generators do |g|
g.orm :active_record
g.template_engine :erb
g.test_framework :shoulda, :fixture => false
g.stylesheets false
# Add a fallback!
g.fallbacks[:shoulda] = :test_unit
end
</pre>
</div>
</notextile>
<p>Now, if you create a Comment scaffold, you will see that the shoulda generators are being invoked, and at the end, they are just falling back to TestUnit generators:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate scaffold Comment body:text
invoke active_record
create db/migrate/20091120151323_create_comments.rb
create app/models/comment.rb
invoke shoulda
create test/unit/comment_test.rb
create test/fixtures/comments.yml
route map.resources :comments
invoke scaffold_controller
create app/controllers/comments_controller.rb
invoke erb
create app/views/comments
create app/views/comments/index.html.erb
create app/views/comments/edit.html.erb
create app/views/comments/show.html.erb
create app/views/comments/new.html.erb
create app/views/comments/_form.html.erb
create app/views/layouts/comments.html.erb
invoke shoulda
create test/functional/comments_controller_test.rb
invoke my_helper
create app/helpers/comments_helper.rb
invoke shoulda
create test/unit/helpers/comments_helper_test.rb
</pre>
</div>
</notextile>
<p>Fallbacks allow your generators to have a single responsibility, increasing code reuse and reducing the amount of duplication.</p>
<h3 id="application-templates">8 Application templates</h3>
<p>Now that you’ve seen how generators can be used <em>inside</em> an application, did you know they can also be used to <em>generate</em> applications too? This kind of generator is referred as a “template”.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
gem("rspec-rails", :group => "test")
gem("cucumber-rails", :group => "test")
if yes?("Would you like to install Devise?")
gem("devise")
generate("devise:install")
model_name = ask("What would you like the user model to be called? [user]")
model_name = "user" if model_name.blank?
generate("devise", model_name)
end
</pre>
</div>
</notextile>
<p>In the above template we specify that the application relies on the <tt>rspec-rails</tt> and <tt>cucumber-rails</tt> gem so these two will be added to the <tt>test</tt> group in the <tt>Gemfile</tt>. Then we pose a question to the user about whether or not they would like to install Devise. If the user replies “y” or “yes” to this question, then the template will add Devise to the <tt>Gemfile</tt> outside of any group and then runs the <tt>devise:install</tt> generator. This template then takes the users input and runs the <tt>devise</tt> generator, with the user’s answer from the last question being passed to this generator.</p>
<p>Imagine that this template was in a file called <tt>template.rb</tt>. We can use it to modify the outcome of the <tt>rails new</tt> command by using the <tt>-m</tt> option and passing in the filename:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
rails new thud -m template.rb
</pre>
</div>
</notextile>
<p>This command will generate the <tt>Thud</tt> application, and then apply the template to the generated output.</p>
<p>Templates don’t have to be stored on the local system, the <tt>-m</tt> option also supports online templates:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
rails new thud -m https://gist.github.com/722911.txt
</pre>
</div>
</notextile>
<p>Whilst the final section of this guide doesn’t cover how to generate the most awesome template known to man, it will take you through the methods available at your disposal so that you can develop it yourself. These same methods are also available for generators.</p>
<h3 id="generator-methods">9 Generator methods</h3>
<p>The following are methods available for both generators and templates for Rails.</p>
<div class='note'><p>Methods provided by Thor are not covered this guide and can be found in <a href="http://rdoc.info/github/wycats/thor/master/Thor/Actions.html">Thor’s documentation</a></p></div>
<h4 id="plugin">9.1 <tt>plugin</tt></h4>
<p><tt>plugin</tt> will install a plugin into the current application.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
plugin("dynamic-form", :git => "git://github.com/rails/dynamic-form.git")
</pre>
</div>
</notextile>
<p>Available options are:</p>
<ul>
<li><tt>:git</tt> – Takes the path to the git repository where this plugin can be found.</li>
<li><tt>:branch</tt> – The name of the branch of the git repository where the plugin is found.</li>
<li><tt>:submodule</tt> – Set to <tt>true</tt> for the plugin to be installed as a submodule. Defaults to <tt>false</tt>.</li>
<li><tt>:svn</tt> – Takes the path to the svn repository where this plugin can be found.</li>
<li><tt>:revision</tt> – The revision of the plugin in an <span class="caps">SVN</span> repository.</li>
</ul>
<h4 id="gem">9.2 <tt>gem</tt></h4>
<p>Specifies a gem dependency of the application.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
gem("rspec", :group => "test", :version => "2.1.0")
gem("devise", "1.1.5")
</pre>
</div>
</notextile>
<p>Available options are:</p>
<ul>
<li><tt>:group</tt> – The group in the <tt>Gemfile</tt> where this gem should go.</li>
<li><tt>:version</tt> – The version string of the gem you want to use. Can also be specified as the second argument to the method.</li>
<li><tt>:git</tt> – The <span class="caps">URL</span> to the git repository for this gem.</li>
</ul>
<p>Any additional options passed to this method are put on the end of the line:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
gem("devise", :git => "git://github.com/plataformatec/devise", :branch => "master")
</pre>
</div>
</notextile>
<p>The above code will put the following line into <tt>Gemfile</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
gem "devise", :git => "git://github.com/plataformatec/devise", :branch => "master"
</pre>
</div>
</notextile>
<h4 id="add_source">9.3 <tt>add_source</tt></h4>
<p>Adds a specified source to <tt>Gemfile</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
add_source "http://gems.github.com"
</pre>
</div>
</notextile>
<h4 id="application">9.4 <tt>application</tt></h4>
<p>Adds a line to <tt>config/application.rb</tt> directly after the application class definition.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
application "config.asset_host = 'http://example.com'"
</pre>
</div>
</notextile>
<p>This method can also take a block:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
application do
"config.asset_host = 'http://example.com'"
end
</pre>
</div>
</notextile>
<p>Available options are:</p>
<ul>
<li><tt>:env</tt> – Specify an environment for this configuration option. If you wish to use this option with the block syntax the recommended syntax is as follows:</li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
application(nil, :env => "development") do
"config.asset_host = 'http://localhost:3000'"
end
</pre>
</div>
</notextile>
<h4 id="git">9.5 <tt>git</tt></h4>
<p>Runs the specified git command:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
git :init
git :add => "."
git :commit => "-m First commit!"
git :add => "onefile.rb", :rm => "badfile.cxx"
</pre>
</div>
</notextile>
<p>The values of the hash here being the arguments or options passed to the specific git command. As per the final example shown here, multiple git commands can be specified at a time, but the order of their running is not guaranteed to be the same as the order that they were specified in.</p>
<h4 id="vendor">9.6 <tt>vendor</tt></h4>
<p>Places a file into <tt>vendor</tt> which contains the specified code.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
vendor("sekrit.rb", '#top secret stuff')
</pre>
</div>
</notextile>
<p>This method also takes a block:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
vendor("seeds.rb") do
"puts 'in ur app, seeding ur database'"
end
</pre>
</div>
</notextile>
<h4 id="lib">9.7 <tt>lib</tt></h4>
<p>Places a file into <tt>lib</tt> which contains the specified code.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
lib("special.rb", 'p Rails.root')
</pre>
</div>
</notextile>
<p>This method also takes a block:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
lib("super_special.rb") do
puts "Super special!"
end
</pre>
</div>
</notextile>
<h4 id="rakefile">9.8 <tt>rakefile</tt></h4>
<p>Creates a Rake file in the <tt>lib/tasks</tt> directory of the application.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
rakefile("test.rake", 'hello there')
</pre>
</div>
</notextile>
<p>This method also takes a block:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
rakefile("test.rake") do
%Q{
task :rock => :environment do
puts "Rockin'"
end
}
end
</pre>
</div>
</notextile>
<h4 id="initializer">9.9 <tt>initializer</tt></h4>
<p>Creates an initializer in the <tt>config/initializers</tt> directory of the application:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
initializer("begin.rb", "puts 'this is the beginning'")
</pre>
</div>
</notextile>
<p>This method also takes a block:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
initializer("begin.rb") do
puts "Almost done!"
end
</pre>
</div>
</notextile>
<h4 id="generate">9.10 <tt>generate</tt></h4>
<p>Runs the specified generator where the first argument is the generator name and the remaining arguments are passed directly to the generator.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
generate("scaffold", "forums title:string description:text")
</pre>
</div>
</notextile>
<h4 id="rake">9.11 <tt>rake</tt></h4>
<p>Runs the specified Rake task.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
rake("db:migrate")
</pre>
</div>
</notextile>
<p>Available options are:</p>
<ul>
<li><tt>:env</tt> – Specifies the environment in which to run this rake task.</li>
<li><tt>:sudo</tt> – Whether or not to run this task using <tt>sudo</tt>. Defaults to <tt>false</tt>.</li>
</ul>
<h4 id="capify">9.12 <tt>capify!</tt></h4>
<p>Runs the <tt>capify</tt> command from Capistrano at the root of the application which generates Capistrano configuration.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
capify!
</pre>
</div>
</notextile>
<h4 id="route">9.13 <tt>route</tt></h4>
<p>Adds text to the <tt>config/routes.rb</tt> file:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
route("resources :people")
</pre>
</div>
</notextile>
<h4 id="readme">9.14 <tt>readme</tt></h4>
<p>Output the contents of a file in the template’s <tt>source_path</tt>, usually a <span class="caps">README</span>.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
readme("README")
</pre>
</div>
</notextile>
<h3 id="changelog">10 Changelog</h3>
<ul>
<li>December 1, 2010: Documenting the available methods and options for generators and templates by <a href="http://ryanbigg.com">Ryan Bigg</a></li>
<li>December 1, 2010: Addition of Rails application templates by <a href="http://ryanbigg.com">Ryan Bigg</a></li>
</ul>
<ul>
<li>August 23, 2010: Edit pass by <a href="credits.html#fxn">Xavier Noria</a></li>
</ul>
<ul>
<li>April 30, 2010: Reviewed by José Valim</li>
</ul>
<ul>
<li>November 20, 2009: First version by José Valim</li>
</ul>
<h3>Feedback</h3>
<p>
You're encouraged to help in keeping the quality of this guide.
</p>
<p>
If you see any typos or factual errors you are confident to
patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
and push the change yourself. That branch of Rails has public write access.
Commits are still reviewed, but that happens after you've submitted your
contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
cross-merged with master periodically.
</p>
<p>
You may also find incomplete content, or stuff that is not up to date.
Please do add any missing documentation for master. Check the
<a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
for style and conventions.
</p>
<p>
Issues may also be reported in <a href="https://github.com/lifo/docrails/issues">Github</a>.
</p>
<p>And last but not least, any kind of discussion regarding Ruby on Rails
documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
</p>
</div>
</div>
</div>
<hr class="hide" />
<div id="footer">
<div class="wrapper">
<p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
</div>
</div>
<script type="text/javascript" src="javascripts/guides.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
<script type="text/javascript">
SyntaxHighlighter.all()
</script>
</body>
</html>