-
Notifications
You must be signed in to change notification settings - Fork 0
/
engines.html
1471 lines (1343 loc) · 78.8 KB
/
engines.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
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Getting Started with Engines — Ruby on Rails 指南</title>
<meta name="description" content="Ruby on Rails 指南:系統學習 Rails(Rails 4.2 版本)" >
<meta name="keywords" content="Ruby on Rails Guides 指南 中文 學習 免費 網路 Web 開發" >
<meta name="author" content="http://git.io/G_R1sA">
<meta property="fb:admins" content="1340181291">
<meta property="og:title" content="Getting Started with Engines — Ruby on Rails 指南" >
<meta property="og:site_name" content="Ruby on Rails 指南">
<meta property="og:image" content="http://rails.ruby.tw/images/rails_guides_cover.jpg">
<meta property="og:url" content="http://rails.ruby.tw/">
<meta property="og:type" content="article">
<meta property="og:description" content="Ruby on Rails 指南:系統學習 Rails(Rails 4.2 版本)">
<link rel="stylesheet" href="stylesheets/application.css">
<link href="http://fonts.googleapis.com/css?family=Noto+Sans:400,700|Noto+Serif:700|Source+Code+Pro" rel="stylesheet">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon">
</head>
<body class="guide">
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/zh-TW/sdk.js#xfbml=1&appId=837401439623727&version=v2.0";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<script type="text/javascript">
window.twttr=(function(d,s,id){var t,js,fjs=d.getElementsByTagName(s)[0];if(d.getElementById(id)){return}js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);return window.twttr||(t={_e:[],ready:function(f){t._e.push(f)}})}(document,"script","twitter-wjs"));
</script>
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">更多內容 <a href="http://rubyonrails.org/">rubyonrails.org:</a></strong>
<span class="red-button more-info-button">
更多內容
</span>
<ul class="more-info-links s-hidden">
<li class="more-info"><a href="http://rubyonrails.org/">綜覽</a></li>
<li class="more-info"><a href="http://rubyonrails.org/download">下載</a></li>
<li class="more-info"><a href="http://rubyonrails.org/deploy">部署</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">原始碼</a></li>
<li class="more-info"><a href="http://rubyonrails.org/screencasts">影片</a></li>
<li class="more-info"><a href="http://rubyonrails.org/documentation">文件</a></li>
<li class="more-info"><a href="http://rubyonrails.org/community">社群</a></li>
<li class="more-info"><a href="http://weblog.rubyonrails.org/">Blog</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="回首頁">Guides.rubyonrails.org</a></h1>
<ul class="nav">
<li><a class="nav-item" href="index.html">首頁</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">指南目錄</a>
<div id="guides" class="clearfix" style="display: none;">
<hr>
<dl class="L">
<dt>起步走</dt>
<dd><a href="getting_started.html">Rails 起步走</a></dd>
<dt>Models</dt>
<dd><a href="active_record_basics.html">Active Record 基礎</a></dd>
<dd><a href="active_record_migrations.html">Active Record 遷移</a></dd>
<dd><a href="active_record_validations.html">Active Record 驗證</a></dd>
<dd><a href="active_record_callbacks.html">Active Record 回呼</a></dd>
<dd><a href="association_basics.html">Active Record 關聯</a></dd>
<dd><a href="active_record_querying.html">Active Record 查詢</a></dd>
<dt>Views</dt>
<dd><a href="layouts_and_rendering.html">Rails 算繪與版型</a></dd>
<dd><a href="form_helpers.html">Action View 表單輔助方法</a></dd>
<dt>Controllers</dt>
<dd><a href="action_controller_overview.html">Action Controller 綜覽</a></dd>
<dd><a href="routing.html">Rails 路由:深入淺出</a></dd>
</dl>
<dl class="R">
<dt>深入了解</dt>
<dd><a href="active_support_core_extensions.html">Active Support 核心擴展</a></dd>
<dd><a href="i18n.html">Rails 國際化 API</a></dd>
<dd><a href="action_mailer_basics.html">Action Mailer 基礎</a></dd>
<dd><a href="active_job_basics.html">Active Job 基礎</a></dd>
<dd><a href="security.html">Rails 安全指南</a></dd>
<dd><a href="debugging_rails_applications.html">除錯 Rails 應用程式</a></dd>
<dd><a href="configuring.html">Rails 應用程式設定</a></dd>
<dd><a href="command_line.html">Rake 任務與 Rails 命令列工具</a></dd>
<dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
<dd><a href="working_with_javascript_in_rails.html">在 Rails 使用 JavaScript</a></dd>
<dd><a href="constant_autoloading_and_reloading.html">Constant Autoloading and Reloading</a></dd>
<dt>擴充 Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">客製與新建 Rails 產生器</a></dd>
<dd><a href="rails_application_templates.html">Rails 應用程式模版</a></dd>
<dt>貢獻 Ruby on Rails</dt>
<dd><a href="contributing_to_ruby_on_rails.html">貢獻 Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API 文件準則</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails 指南準則</a></dd>
<dt>維護方針</dt>
<dd><a href="maintenance_policy.html">維護方針</a></dd>
<dt>發佈記</dt>
<dd><a href="upgrading_ruby_on_rails.html">升級 Ruby on Rails</a></dd>
<dd><a href="4_2_release_notes.html">Ruby on Rails 4.2 發佈記</a></dd>
<dd><a href="4_1_release_notes.html">Ruby on Rails 4.1 發佈記</a></dd>
<dd><a href="4_0_release_notes.html">Ruby on Rails 4.0 發佈記</a></dd>
<dd><a href="3_2_release_notes.html">Ruby on Rails 3.2 發佈記</a></dd>
<dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 發佈記</a></dd>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 發佈記</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 發佈記</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 發佈記</a></dd>
<dt>Rails 指南翻譯術語</dt>
<dd><a href="translation_terms.html">翻譯術語</a></dd>
</dl>
</div>
</li>
<li><a class="nav-item" href="//github.com/docrails-tw/guides">貢獻翻譯</a></li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">貢獻</a></li>
<li><a class="nav-item" href="credits.html">致謝</a></li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">指南目錄</option>
<optgroup label="起步走">
<option value="getting_started.html">Rails 起步走</option>
</optgroup>
<optgroup label="Models">
<option value="active_record_basics.html">Active Record 基礎</option>
<option value="active_record_migrations.html">Active Record 遷移</option>
<option value="active_record_validations.html">Active Record 驗證</option>
<option value="active_record_callbacks.html">Active Record 回呼</option>
<option value="association_basics.html">Active Record 關聯</option>
<option value="active_record_querying.html">Active Record 查詢</option>
</optgroup>
<optgroup label="Views">
<option value="layouts_and_rendering.html">Rails 算繪與版型</option>
<option value="form_helpers.html">Action View 表單輔助方法</option>
</optgroup>
<optgroup label="Controllers">
<option value="action_controller_overview.html">Action Controller 綜覽</option>
<option value="routing.html">Rails 路由:深入淺出</option>
</optgroup>
<optgroup label="深入了解">
<option value="active_support_core_extensions.html">Active Support 核心擴展</option>
<option value="i18n.html">Rails 國際化 API</option>
<option value="action_mailer_basics.html">Action Mailer 基礎</option>
<option value="active_job_basics.html">Active Job 基礎</option>
<option value="security.html">Rails 安全指南</option>
<option value="debugging_rails_applications.html">除錯 Rails 應用程式</option>
<option value="configuring.html">Rails 應用程式設定</option>
<option value="command_line.html">Rake 任務與 Rails 命令列工具</option>
<option value="asset_pipeline.html">Asset Pipeline</option>
<option value="working_with_javascript_in_rails.html">在 Rails 使用 JavaScript</option>
<option value="constant_autoloading_and_reloading.html">Constant Autoloading and Reloading</option>
</optgroup>
<optgroup label="擴充 Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">客製與新建 Rails 產生器</option>
<option value="rails_application_templates.html">Rails 應用程式模版</option>
</optgroup>
<optgroup label="貢獻 Ruby on Rails">
<option value="contributing_to_ruby_on_rails.html">貢獻 Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API 文件準則</option>
<option value="ruby_on_rails_guides_guidelines.html">Ruby on Rails 指南準則</option>
</optgroup>
<optgroup label="維護方針">
<option value="maintenance_policy.html">維護方針</option>
</optgroup>
<optgroup label="發佈記">
<option value="upgrading_ruby_on_rails.html">升級 Ruby on Rails</option>
<option value="4_2_release_notes.html">Ruby on Rails 4.2 發佈記</option>
<option value="4_1_release_notes.html">Ruby on Rails 4.1 發佈記</option>
<option value="4_0_release_notes.html">Ruby on Rails 4.0 發佈記</option>
<option value="3_2_release_notes.html">Ruby on Rails 3.2 發佈記</option>
<option value="3_1_release_notes.html">Ruby on Rails 3.1 發佈記</option>
<option value="3_0_release_notes.html">Ruby on Rails 3.0 發佈記</option>
<option value="2_3_release_notes.html">Ruby on Rails 2.3 發佈記</option>
<option value="2_2_release_notes.html">Ruby on Rails 2.2 發佈記</option>
</optgroup>
<optgroup label="Rails 指南翻譯術語">
<option value="translation_terms.html">翻譯術語</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
</div>
<hr class="hide">
<div id="feature">
<div class="wrapper">
<h2>Getting Started with Engines</h2><p>In this guide you will learn about engines and how they can be used to provide
additional functionality to their host applications through a clean and very
easy-to-use interface.</p><p>After reading this guide, you will know:</p>
<ul>
<li>What makes an engine.</li>
<li>How to generate an engine.</li>
<li>Building features for the engine.</li>
<li>Hooking the engine into an application.</li>
<li>Overriding engine functionality in the application.</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#what-are-engines-questionmark">What are engines?</a></li>
<li>
<a href="#generating-an-engine">Generating an engine</a>
<ul>
<li><a href="#inside-an-engine">Inside an Engine</a></li>
</ul>
</li>
<li>
<a href="#providing-engine-functionality">Providing engine functionality</a>
<ul>
<li><a href="#generating-an-article-resource">Generating an Article Resource</a></li>
<li><a href="#generating-a-comments-resource">Generating a Comments Resource</a></li>
</ul>
</li>
<li>
<a href="#hooking-into-an-application">Hooking Into an Application</a>
<ul>
<li><a href="#mounting-the-engine">Mounting the Engine</a></li>
<li><a href="#engine-setup">Engine setup</a></li>
<li><a href="#using-a-class-provided-by-the-application">Using a Class Provided by the Application</a></li>
<li><a href="#configuring-an-engine">Configuring an Engine</a></li>
</ul>
</li>
<li>
<a href="#testing-an-engine">Testing an engine</a>
<ul>
<li><a href="#functional-tests">Functional Tests</a></li>
</ul>
</li>
<li>
<a href="#improving-engine-functionality">Improving engine functionality</a>
<ul>
<li><a href="#overriding-models-and-controllers">Overriding Models and Controllers</a></li>
<li><a href="#overriding-views">Overriding Views</a></li>
<li><a href="#routes">Routes</a></li>
<li><a href="#assets">Assets</a></li>
<li><a href="#separate-assets-precompiling">Separate Assets & Precompiling</a></li>
<li><a href="#other-gem-dependencies">Other Gem Dependencies</a></li>
</ul>
</li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="what-are-engines-questionmark">1 What are engines?</h3><p>Engines can be considered miniature applications that provide functionality to
their host applications. A Rails application is actually just a "supercharged"
engine, with the <code>Rails::Application</code> class inheriting a lot of its behavior
from <code>Rails::Engine</code>.</p><p>Therefore, engines and applications can be thought of almost the same thing,
just with subtle differences, as you'll see throughout this guide. Engines and
applications also share a common structure.</p><p>Engines are also closely related to plugins. The two share a common <code>lib</code>
directory structure, and are both generated using the <code>rails plugin new</code>
generator. The difference is that an engine is considered a "full plugin" by
Rails (as indicated by the <code>--full</code> option that's passed to the generator
command). We'll actually be using the <code>--mountable</code> option here, which includes
all the features of <code>--full</code>, and then some. This guide will refer to these
"full plugins" simply as "engines" throughout. An engine <strong>can</strong> be a plugin,
and a plugin <strong>can</strong> be an engine.</p><p>The engine that will be created in this guide will be called "blorgh". This
engine will provide blogging functionality to its host applications, allowing
for new articles and comments to be created. At the beginning of this guide, you
will be working solely within the engine itself, but in later sections you'll
see how to hook it into an application.</p><p>Engines can also be isolated from their host applications. This means that an
application is able to have a path provided by a routing helper such as
<code>articles_path</code> and use an engine also that provides a path also called
<code>articles_path</code>, and the two would not clash. Along with this, controllers, models
and table names are also namespaced. You'll see how to do this later in this
guide.</p><p>It's important to keep in mind at all times that the application should
<strong>always</strong> take precedence over its engines. An application is the object that
has final say in what goes on in its environment. The engine should
only be enhancing it, rather than changing it drastically.</p><p>To see demonstrations of other engines, check out
<a href="https://github.com/plataformatec/devise">Devise</a>, an engine that provides
authentication for its parent applications, or
<a href="https://github.com/radar/forem">Forem</a>, an engine that provides forum
functionality. There's also <a href="https://github.com/spree/spree">Spree</a> which
provides an e-commerce platform, and
<a href="https://github.com/refinery/refinerycms">RefineryCMS</a>, a CMS engine.</p><p>Finally, engines would not have been possible without the work of James Adam,
Piotr Sarnacki, the Rails Core Team, and a number of other people. If you ever
meet them, don't forget to say thanks!</p><h3 id="generating-an-engine">2 Generating an engine</h3><p>To generate an engine, you will need to run the plugin generator and pass it
options as appropriate to the need. For the "blorgh" example, you will need to
create a "mountable" engine, running this command in a terminal:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails plugin new blorgh --mountable
</pre>
</div>
<p>The full list of options for the plugin generator may be seen by typing:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails plugin --help
</pre>
</div>
<p>The <code>--mountable</code> option tells the generator that you want to create a
"mountable" and namespace-isolated engine. This generator will provide the same
skeleton structure as would the <code>--full</code> option. The <code>--full</code> option tells the
generator that you want to create an engine, including a skeleton structure
that provides the following:</p>
<ul>
<li>An <code>app</code> directory tree</li>
<li>
<p>A <code>config/routes.rb</code> file:</p>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Rails.application.routes.draw do
end
</pre>
</div>
</li>
<li>
<p>A file at <code>lib/blorgh/engine.rb</code>, which is identical in function to a
standard Rails application's <code>config/application.rb</code> file:</p>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module Blorgh
class Engine < ::Rails::Engine
end
end
</pre>
</div>
</li>
</ul>
<p>The <code>--mountable</code> option will add to the <code>--full</code> option:</p>
<ul>
<li>Asset manifest files (<code>application.js</code> and <code>application.css</code>)</li>
<li>A namespaced <code>ApplicationController</code> stub</li>
<li>A namespaced <code>ApplicationHelper</code> stub</li>
<li>A layout view template for the engine</li>
<li>
<p>Namespace isolation to <code>config/routes.rb</code>:</p>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Blorgh::Engine.routes.draw do
end
</pre>
</div>
</li>
<li>
<p>Namespace isolation to <code>lib/blorgh/engine.rb</code>:</p>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module Blorgh
class Engine < ::Rails::Engine
isolate_namespace Blorgh
end
end
</pre>
</div>
</li>
</ul>
<p>Additionally, the <code>--mountable</code> option tells the generator to mount the engine
inside the dummy testing application located at <code>test/dummy</code> by adding the
following to the dummy application's routes file at
<code>test/dummy/config/routes.rb</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
mount Blorgh::Engine, at: "blorgh"
</pre>
</div>
<h4 id="inside-an-engine">2.1 Inside an Engine</h4><h5 id="critical-files">2.1.1 Critical Files</h5><p>At the root of this brand new engine's directory lives a <code>blorgh.gemspec</code> file.
When you include the engine into an application later on, you will do so with
this line in the Rails application's <code>Gemfile</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
gem 'blorgh', path: "vendor/engines/blorgh"
</pre>
</div>
<p>Don't forget to run <code>bundle install</code> as usual. By specifying it as a gem within
the <code>Gemfile</code>, Bundler will load it as such, parsing this <code>blorgh.gemspec</code> file
and requiring a file within the <code>lib</code> directory called <code>lib/blorgh.rb</code>. This
file requires the <code>blorgh/engine.rb</code> file (located at <code>lib/blorgh/engine.rb</code>)
and defines a base module called <code>Blorgh</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require "blorgh/engine"
module Blorgh
end
</pre>
</div>
<div class="info"><p>Some engines choose to use this file to put global configuration options
for their engine. It's a relatively good idea, so if you want to offer
configuration options, the file where your engine's <code>module</code> is defined is
perfect for that. Place the methods inside the module and you'll be good to go.</p></div><p>Within <code>lib/blorgh/engine.rb</code> is the base class for the engine:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module Blorgh
class Engine < Rails::Engine
isolate_namespace Blorgh
end
end
</pre>
</div>
<p>By inheriting from the <code>Rails::Engine</code> class, this gem notifies Rails that
there's an engine at the specified path, and will correctly mount the engine
inside the application, performing tasks such as adding the <code>app</code> directory of
the engine to the load path for models, mailers, controllers and views.</p><p>The <code>isolate_namespace</code> method here deserves special notice. This call is
responsible for isolating the controllers, models, routes and other things into
their own namespace, away from similar components inside the application.
Without this, there is a possibility that the engine's components could "leak"
into the application, causing unwanted disruption, or that important engine
components could be overridden by similarly named things within the application.
One of the examples of such conflicts is helpers. Without calling
<code>isolate_namespace</code>, the engine's helpers would be included in an application's
controllers.</p><div class="note"><p>It is <strong>highly</strong> recommended that the <code>isolate_namespace</code> line be left
within the <code>Engine</code> class definition. Without it, classes generated in an engine
<strong>may</strong> conflict with an application.</p></div><p>What this isolation of the namespace means is that a model generated by a call
to <code>bin/rails g model</code>, such as <code>bin/rails g model article</code>, won't be called <code>Article</code>, but
instead be namespaced and called <code>Blorgh::Article</code>. In addition, the table for the
model is namespaced, becoming <code>blorgh_articles</code>, rather than simply <code>articles</code>.
Similar to the model namespacing, a controller called <code>ArticlesController</code> becomes
<code>Blorgh::ArticlesController</code> and the views for that controller will not be at
<code>app/views/articles</code>, but <code>app/views/blorgh/articles</code> instead. Mailers are namespaced
as well.</p><p>Finally, routes will also be isolated within the engine. This is one of the most
important parts about namespacing, and is discussed later in the
<a href="#routes">Routes</a> section of this guide.</p><h5 id="app-directory">2.1.2 <code>app</code> Directory</h5><p>Inside the <code>app</code> directory are the standard <code>assets</code>, <code>controllers</code>, <code>helpers</code>,
<code>mailers</code>, <code>models</code> and <code>views</code> directories that you should be familiar with
from an application. The <code>helpers</code>, <code>mailers</code> and <code>models</code> directories are
empty, so they aren't described in this section. We'll look more into models in
a future section, when we're writing the engine.</p><p>Within the <code>app/assets</code> directory, there are the <code>images</code>, <code>javascripts</code> and
<code>stylesheets</code> directories which, again, you should be familiar with due to their
similarity to an application. One difference here, however, is that each
directory contains a sub-directory with the engine name. Because this engine is
going to be namespaced, its assets should be too.</p><p>Within the <code>app/controllers</code> directory there is a <code>blorgh</code> directory that
contains a file called <code>application_controller.rb</code>. This file will provide any
common functionality for the controllers of the engine. The <code>blorgh</code> directory
is where the other controllers for the engine will go. By placing them within
this namespaced directory, you prevent them from possibly clashing with
identically-named controllers within other engines or even within the
application.</p><div class="note"><p>The <code>ApplicationController</code> class inside an engine is named just like a
Rails application in order to make it easier for you to convert your
applications into engines.</p></div><p>Lastly, the <code>app/views</code> directory contains a <code>layouts</code> folder, which contains a
file at <code>blorgh/application.html.erb</code>. This file allows you to specify a layout
for the engine. If this engine is to be used as a stand-alone engine, then you
would add any customization to its layout in this file, rather than the
application's <code>app/views/layouts/application.html.erb</code> file.</p><p>If you don't want to force a layout on to users of the engine, then you can
delete this file and reference a different layout in the controllers of your
engine.</p><h5 id="bin-directory">2.1.3 <code>bin</code> Directory</h5><p>This directory contains one file, <code>bin/rails</code>, which enables you to use the
<code>rails</code> sub-commands and generators just like you would within an application.
This means that you will be able to generate new controllers and models for this
engine very easily by running commands like this:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ bin/rails g model
</pre>
</div>
<p>Keep in mind, of course, that anything generated with these commands inside of
an engine that has <code>isolate_namespace</code> in the <code>Engine</code> class will be namespaced.</p><h5 id="test-directory">2.1.4 <code>test</code> Directory</h5><p>The <code>test</code> directory is where tests for the engine will go. To test the engine,
there is a cut-down version of a Rails application embedded within it at
<code>test/dummy</code>. This application will mount the engine in the
<code>test/dummy/config/routes.rb</code> file:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Rails.application.routes.draw do
mount Blorgh::Engine => "/blorgh"
end
</pre>
</div>
<p>This line mounts the engine at the path <code>/blorgh</code>, which will make it accessible
through the application only at that path.</p><p>Inside the test directory there is the <code>test/integration</code> directory, where
integration tests for the engine should be placed. Other directories can be
created in the <code>test</code> directory as well. For example, you may wish to create a
<code>test/models</code> directory for your model tests.</p><h3 id="providing-engine-functionality">3 Providing engine functionality</h3><p>The engine that this guide covers provides submitting articles and commenting
functionality and follows a similar thread to the <a href="getting_started.html">Getting Started
Guide</a>, with some new twists.</p><h4 id="generating-an-article-resource">3.1 Generating an Article Resource</h4><p>The first thing to generate for a blog engine is the <code>Article</code> model and related
controller. To quickly generate this, you can use the Rails scaffold generator.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ bin/rails generate scaffold article title:string text:text
</pre>
</div>
<p>This command will output this information:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
invoke active_record
create db/migrate/[timestamp]_create_blorgh_articles.rb
create app/models/blorgh/article.rb
invoke test_unit
create test/models/blorgh/article_test.rb
create test/fixtures/blorgh/articles.yml
invoke resource_route
route resources :articles
invoke scaffold_controller
create app/controllers/blorgh/articles_controller.rb
invoke erb
create app/views/blorgh/articles
create app/views/blorgh/articles/index.html.erb
create app/views/blorgh/articles/edit.html.erb
create app/views/blorgh/articles/show.html.erb
create app/views/blorgh/articles/new.html.erb
create app/views/blorgh/articles/_form.html.erb
invoke test_unit
create test/controllers/blorgh/articles_controller_test.rb
invoke helper
create app/helpers/blorgh/articles_helper.rb
invoke assets
invoke js
create app/assets/javascripts/blorgh/articles.js
invoke css
create app/assets/stylesheets/blorgh/articles.css
invoke css
create app/assets/stylesheets/scaffold.css
</pre>
</div>
<p>The first thing that the scaffold generator does is invoke the <code>active_record</code>
generator, which generates a migration and a model for the resource. Note here,
however, that the migration is called <code>create_blorgh_articles</code> rather than the
usual <code>create_articles</code>. This is due to the <code>isolate_namespace</code> method called in
the <code>Blorgh::Engine</code> class's definition. The model here is also namespaced,
being placed at <code>app/models/blorgh/article.rb</code> rather than <code>app/models/article.rb</code> due
to the <code>isolate_namespace</code> call within the <code>Engine</code> class.</p><p>Next, the <code>test_unit</code> generator is invoked for this model, generating a model
test at <code>test/models/blorgh/article_test.rb</code> (rather than
<code>test/models/article_test.rb</code>) and a fixture at <code>test/fixtures/blorgh/articles.yml</code>
(rather than <code>test/fixtures/articles.yml</code>).</p><p>After that, a line for the resource is inserted into the <code>config/routes.rb</code> file
for the engine. This line is simply <code>resources :articles</code>, turning the
<code>config/routes.rb</code> file for the engine into this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Blorgh::Engine.routes.draw do
resources :articles
end
</pre>
</div>
<p>Note here that the routes are drawn upon the <code>Blorgh::Engine</code> object rather than
the <code>YourApp::Application</code> class. This is so that the engine routes are confined
to the engine itself and can be mounted at a specific point as shown in the
<a href="#test-directory">test directory</a> section. It also causes the engine's routes to
be isolated from those routes that are within the application. The
<a href="#routes">Routes</a> section of this guide describes it in detail.</p><p>Next, the <code>scaffold_controller</code> generator is invoked, generating a controller
called <code>Blorgh::ArticlesController</code> (at
<code>app/controllers/blorgh/articles_controller.rb</code>) and its related views at
<code>app/views/blorgh/articles</code>. This generator also generates a test for the
controller (<code>test/controllers/blorgh/articles_controller_test.rb</code>) and a helper
(<code>app/helpers/blorgh/articles_controller.rb</code>).</p><p>Everything this generator has created is neatly namespaced. The controller's
class is defined within the <code>Blorgh</code> module:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module Blorgh
class ArticlesController < ApplicationController
...
end
end
</pre>
</div>
<div class="note"><p>The <code>ApplicationController</code> class being inherited from here is the
<code>Blorgh::ApplicationController</code>, not an application's <code>ApplicationController</code>.</p></div><p>The helper inside <code>app/helpers/blorgh/articles_helper.rb</code> is also namespaced:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module Blorgh
module ArticlesHelper
...
end
end
</pre>
</div>
<p>This helps prevent conflicts with any other engine or application that may have
an article resource as well.</p><p>Finally, the assets for this resource are generated in two files:
<code>app/assets/javascripts/blorgh/articles.js</code> and
<code>app/assets/stylesheets/blorgh/articles.css</code>. You'll see how to use these a little
later.</p><p>By default, the scaffold styling is not applied to the engine because the
engine's layout file, <code>app/views/layouts/blorgh/application.html.erb</code>, doesn't
load it. To make the scaffold styling apply, insert this line into the <code><head></code>
tag of this layout:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= stylesheet_link_tag "scaffold" %>
</pre>
</div>
<p>You can see what the engine has so far by running <code>rake db:migrate</code> at the root
of our engine to run the migration generated by the scaffold generator, and then
running <code>rails server</code> in <code>test/dummy</code>. When you open
<code>http://localhost:3000/blorgh/articles</code> you will see the default scaffold that has
been generated. Click around! You've just generated your first engine's first
functions.</p><p>If you'd rather play around in the console, <code>rails console</code> will also work just
like a Rails application. Remember: the <code>Article</code> model is namespaced, so to
reference it you must call it as <code>Blorgh::Article</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
>> Blorgh::Article.find(1)
=> #<Blorgh::Article id: 1 ...>
</pre>
</div>
<p>One final thing is that the <code>articles</code> resource for this engine should be the root
of the engine. Whenever someone goes to the root path where the engine is
mounted, they should be shown a list of articles. This can be made to happen if
this line is inserted into the <code>config/routes.rb</code> file inside the engine:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
root to: "articles#index"
</pre>
</div>
<p>Now people will only need to go to the root of the engine to see all the articles,
rather than visiting <code>/articles</code>. This means that instead of
<code>http://localhost:3000/blorgh/articles</code>, you only need to go to
<code>http://localhost:3000/blorgh</code> now.</p><h4 id="generating-a-comments-resource">3.2 Generating a Comments Resource</h4><p>Now that the engine can create new articles, it only makes sense to add
commenting functionality as well. To do this, you'll need to generate a comment
model, a comment controller and then modify the articles scaffold to display
comments and allow people to create new ones.</p><p>From the application root, run the model generator. Tell it to generate a
<code>Comment</code> model, with the related table having two columns: a <code>article_id</code> integer
and <code>text</code> text column.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ bin/rails generate model Comment article_id:integer text:text
</pre>
</div>
<p>This will output the following:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
invoke active_record
create db/migrate/[timestamp]_create_blorgh_comments.rb
create app/models/blorgh/comment.rb
invoke test_unit
create test/models/blorgh/comment_test.rb
create test/fixtures/blorgh/comments.yml
</pre>
</div>
<p>This generator call will generate just the necessary model files it needs,
namespacing the files under a <code>blorgh</code> directory and creating a model class
called <code>Blorgh::Comment</code>. Now run the migration to create our blorgh_comments
table:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rake db:migrate
</pre>
</div>
<p>To show the comments on an article, edit <code>app/views/blorgh/articles/show.html.erb</code> and
add this line before the "Edit" link:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<h3>Comments</h3>
<%= render @article.comments %>
</pre>
</div>
<p>This line will require there to be a <code>has_many</code> association for comments defined
on the <code>Blorgh::Article</code> model, which there isn't right now. To define one, open
<code>app/models/blorgh/article.rb</code> and add this line into the model:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
has_many :comments
</pre>
</div>
<p>Turning the model into this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module Blorgh
class Article < ActiveRecord::Base
has_many :comments
end
end
</pre>
</div>
<div class="note"><p>Because the <code>has_many</code> is defined inside a class that is inside the
<code>Blorgh</code> module, Rails will know that you want to use the <code>Blorgh::Comment</code>
model for these objects, so there's no need to specify that using the
<code>:class_name</code> option here.</p></div><p>Next, there needs to be a form so that comments can be created on an article. To
add this, put this line underneath the call to <code>render @article.comments</code> in
<code>app/views/blorgh/articles/show.html.erb</code>:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render "blorgh/comments/form" %>
</pre>
</div>
<p>Next, the partial that this line will render needs to exist. Create a new
directory at <code>app/views/blorgh/comments</code> and in it a new file called
<code>_form.html.erb</code> which has this content to create the required partial:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<h3>New comment</h3>
<%= form_for [@article, @article.comments.build] do |f| %>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<%= f.submit %>
<% end %>
</pre>
</div>
<p>When this form is submitted, it is going to attempt to perform a <code>POST</code> request
to a route of <code>/articles/:article_id/comments</code> within the engine. This route doesn't
exist at the moment, but can be created by changing the <code>resources :articles</code> line
inside <code>config/routes.rb</code> into these lines:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
resources :articles do
resources :comments
end
</pre>
</div>
<p>This creates a nested route for the comments, which is what the form requires.</p><p>The route now exists, but the controller that this route goes to does not. To
create it, run this command from the application root:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ bin/rails g controller comments
</pre>
</div>
<p>This will generate the following things:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
create app/controllers/blorgh/comments_controller.rb
invoke erb
exist app/views/blorgh/comments
invoke test_unit
create test/controllers/blorgh/comments_controller_test.rb
invoke helper
create app/helpers/blorgh/comments_helper.rb
invoke assets
invoke js
create app/assets/javascripts/blorgh/comments.js
invoke css
create app/assets/stylesheets/blorgh/comments.css
</pre>
</div>
<p>The form will be making a <code>POST</code> request to <code>/articles/:article_id/comments</code>, which
will correspond with the <code>create</code> action in <code>Blorgh::CommentsController</code>. This
action needs to be created, which can be done by putting the following lines
inside the class definition in <code>app/controllers/blorgh/comments_controller.rb</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def create
@article = Article.find(params[:article_id])
@comment = @article.comments.create(comment_params)
flash[:notice] = "Comment has been created!"
redirect_to articles_path
end
private
def comment_params
params.require(:comment).permit(:text)
end
</pre>
</div>
<p>This is the final step required to get the new comment form working. Displaying
the comments, however, is not quite right yet. If you were to create a comment
right now, you would see this error:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
Missing partial blorgh/comments/comment with {:handlers=>[:erb, :builder],
:formats=>[:html], :locale=>[:en, :en]}. Searched in: *
"/Users/ryan/Sites/side_projects/blorgh/test/dummy/app/views" *
"/Users/ryan/Sites/side_projects/blorgh/app/views"
</pre>
</div>
<p>The engine is unable to find the partial required for rendering the comments.
Rails looks first in the application's (<code>test/dummy</code>) <code>app/views</code> directory and
then in the engine's <code>app/views</code> directory. When it can't find it, it will throw
this error. The engine knows to look for <code>blorgh/comments/comment</code> because the
model object it is receiving is from the <code>Blorgh::Comment</code> class.</p><p>This partial will be responsible for rendering just the comment text, for now.
Create a new file at <code>app/views/blorgh/comments/_comment.html.erb</code> and put this
line inside it:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= comment_counter + 1 %>. <%= comment.text %>
</pre>
</div>
<p>The <code>comment_counter</code> local variable is given to us by the <code><%= render
@article.comments %></code> call, which will define it automatically and increment the
counter as it iterates through each comment. It's used in this example to
display a small number next to each comment when it's created.</p><p>That completes the comment function of the blogging engine. Now it's time to use
it within an application.</p><h3 id="hooking-into-an-application">4 Hooking Into an Application</h3><p>Using an engine within an application is very easy. This section covers how to
mount the engine into an application and the initial setup required, as well as
linking the engine to a <code>User</code> class provided by the application to provide
ownership for articles and comments within the engine.</p><h4 id="mounting-the-engine">4.1 Mounting the Engine</h4><p>First, the engine needs to be specified inside the application's <code>Gemfile</code>. If
there isn't an application handy to test this out in, generate one using the
<code>rails new</code> command outside of the engine directory like this:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails new unicorn
</pre>
</div>
<p>Usually, specifying the engine inside the Gemfile would be done by specifying it
as a normal, everyday gem.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
gem 'devise'
</pre>
</div>
<p>However, because you are developing the <code>blorgh</code> engine on your local machine,
you will need to specify the <code>:path</code> option in your <code>Gemfile</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
gem 'blorgh', path: "/path/to/blorgh"
</pre>
</div>
<p>Then run <code>bundle</code> to install the gem.</p><p>As described earlier, by placing the gem in the <code>Gemfile</code> it will be loaded when
Rails is loaded. It will first require <code>lib/blorgh.rb</code> from the engine, then
<code>lib/blorgh/engine.rb</code>, which is the file that defines the major pieces of
functionality for the engine.</p><p>To make the engine's functionality accessible from within an application, it
needs to be mounted in that application's <code>config/routes.rb</code> file:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
mount Blorgh::Engine, at: "/blog"
</pre>
</div>
<p>This line will mount the engine at <code>/blog</code> in the application. Making it
accessible at <code>http://localhost:3000/blog</code> when the application runs with <code>rails
server</code>.</p><div class="note"><p>Other engines, such as Devise, handle this a little differently by making
you specify custom helpers (such as <code>devise_for</code>) in the routes. These helpers
do exactly the same thing, mounting pieces of the engines's functionality at a
pre-defined path which may be customizable.</p></div><h4 id="engine-setup">4.2 Engine setup</h4><p>The engine contains migrations for the <code>blorgh_articles</code> and <code>blorgh_comments</code>
table which need to be created in the application's database so that the
engine's models can query them correctly. To copy these migrations into the
application use this command:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rake blorgh:install:migrations
</pre>
</div>
<p>If you have multiple engines that need migrations copied over, use
<code>railties:install:migrations</code> instead:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rake railties:install:migrations
</pre>
</div>
<p>This command, when run for the first time, will copy over all the migrations
from the engine. When run the next time, it will only copy over migrations that
haven't been copied over already. The first run for this command will output
something such as this:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
Copied migration [timestamp_1]_create_blorgh_articles.rb from blorgh
Copied migration [timestamp_2]_create_blorgh_comments.rb from blorgh
</pre>
</div>
<p>The first timestamp (<code>[timestamp_1]</code>) will be the current time, and the second
timestamp (<code>[timestamp_2]</code>) will be the current time plus a second. The reason
for this is so that the migrations for the engine are run after any existing
migrations in the application.</p><p>To run these migrations within the context of the application, simply run <code>rake
db:migrate</code>. When accessing the engine through <code>http://localhost:3000/blog</code>, the
articles will be empty. This is because the table created inside the application is
different from the one created within the engine. Go ahead, play around with the
newly mounted engine. You'll find that it's the same as when it was only an
engine.</p><p>If you would like to run migrations only from one engine, you can do it by
specifying <code>SCOPE</code>:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
rake db:migrate SCOPE=blorgh
</pre>
</div>
<p>This may be useful if you want to revert engine's migrations before removing it.
To revert all migrations from blorgh engine you can run code such as:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
rake db:migrate SCOPE=blorgh VERSION=0
</pre>
</div>
<h4 id="using-a-class-provided-by-the-application">4.3 Using a Class Provided by the Application</h4><h5 id="using-a-model-provided-by-the-application">4.3.1 Using a Model Provided by the Application</h5><p>When an engine is created, it may want to use specific classes from an
application to provide links between the pieces of the engine and the pieces of
the application. In the case of the <code>blorgh</code> engine, making articles and comments
have authors would make a lot of sense.</p><p>A typical application might have a <code>User</code> class that would be used to represent
authors for an article or a comment. But there could be a case where the
application calls this class something different, such as <code>Person</code>. For this
reason, the engine should not hardcode associations specifically for a <code>User</code>
class.</p><p>To keep it simple in this case, the application will have a class called <code>User</code>
that represents the users of the application (we'll get into making this
configurable further on). It can be generated using this command inside the
application:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
rails g model user name:string
</pre>
</div>
<p>The <code>rake db:migrate</code> command needs to be run here to ensure that our
application has the <code>users</code> table for future use.</p><p>Also, to keep it simple, the articles form will have a new text field called
<code>author_name</code>, where users can elect to put their name. The engine will then
take this name and either create a new <code>User</code> object from it, or find one that
already has that name. The engine will then associate the article with the found or
created <code>User</code> object.</p><p>First, the <code>author_name</code> text field needs to be added to the
<code>app/views/blorgh/articles/_form.html.erb</code> partial inside the engine. This can be
added above the <code>title</code> field with this code:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<div class="field">
<%= f.label :author_name %><br>
<%= f.text_field :author_name %>
</div>
</pre>
</div>
<p>Next, we need to update our <code>Blorgh::ArticleController#article_params</code> method to
permit the new form parameter:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def article_params
params.require(:article).permit(:title, :text, :author_name)
end
</pre>
</div>
<p>The <code>Blorgh::Article</code> model should then have some code to convert the <code>author_name</code>
field into an actual <code>User</code> object and associate it as that article's <code>author</code>
before the article is saved. It will also need to have an <code>attr_accessor</code> set up
for this field, so that the setter and getter methods are defined for it.</p><p>To do all this, you'll need to add the <code>attr_accessor</code> for <code>author_name</code>, the
association for the author and the <code>before_save</code> call into
<code>app/models/blorgh/article.rb</code>. The <code>author</code> association will be hard-coded to the
<code>User</code> class for the time being.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
attr_accessor :author_name
belongs_to :author, class_name: "User"
before_save :set_author
private
def set_author
self.author = User.find_or_create_by(name: author_name)
end
</pre>
</div>
<p>By representing the <code>author</code> association's object with the <code>User</code> class, a link
is established between the engine and the application. There needs to be a way
of associating the records in the <code>blorgh_articles</code> table with the records in the
<code>users</code> table. Because the association is called <code>author</code>, there should be an
<code>author_id</code> column added to the <code>blorgh_articles</code> table.</p><p>To generate this new column, run this command within the engine:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ bin/rails g migration add_author_id_to_blorgh_articles author_id:integer
</pre>
</div>
<div class="note"><p>Due to the migration's name and the column specification after it, Rails
will automatically know that you want to add a column to a specific table and
write that into the migration for you. You don't need to tell it any more than
this.</p></div><p>This migration will need to be run on the application. To do that, it must first
be copied using this command:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rake blorgh:install:migrations
</pre>
</div>
<p>Notice that only <em>one</em> migration was copied over here. This is because the first
two migrations were copied over the first time this command was run.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
NOTE Migration [timestamp]_create_blorgh_articles.rb from blorgh has been
skipped. Migration with the same name already exists. NOTE Migration
[timestamp]_create_blorgh_comments.rb from blorgh has been skipped. Migration
with the same name already exists. Copied migration
[timestamp]_add_author_id_to_blorgh_articles.rb from blorgh
</pre>
</div>
<p>Run the migration using:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rake db:migrate
</pre>
</div>
<p>Now with all the pieces in place, an action will take place that will associate
an author - represented by a record in the <code>users</code> table - with an article,
represented by the <code>blorgh_articles</code> table from the engine.</p><p>Finally, the author's name should be displayed on the article's page. Add this code
above the "Title" output inside <code>app/views/blorgh/articles/show.html.erb</code>:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<p>
<b>Author:</b>
<%= @article.author %>
</p>
</pre>
</div>
<p>By outputting <code>@article.author</code> using the <code><%=</code> tag, the <code>to_s</code> method will be
called on the object. By default, this will look quite ugly:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
#<User:0x00000100ccb3b0>
</pre>
</div>
<p>This is undesirable. It would be much better to have the user's name there. To
do this, add a <code>to_s</code> method to the <code>User</code> class within the application:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def to_s
name
end
</pre>
</div>
<p>Now instead of the ugly Ruby object output, the author's name will be displayed.</p><h5 id="using-a-controller-provided-by-the-application">4.3.2 Using a Controller Provided by the Application</h5><p>Because Rails controllers generally share code for things like authentication
and accessing session variables, they inherit from <code>ApplicationController</code> by
default. Rails engines, however are scoped to run independently from the main
application, so each engine gets a scoped <code>ApplicationController</code>. This
namespace prevents code collisions, but often engine controllers need to access