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
/
Copy pathplugins.html
1865 lines (1668 loc) · 68.4 KB
/
plugins.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 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: The Basics of Creating Rails Plugins</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>The Basics of Creating Rails Plugins</h2>
<p>A Rails plugin is either an extension or a modification of the core framework. Plugins provide:</p>
<ul>
<li>a way for developers to share bleeding-edge ideas without hurting the stable code base</li>
<li>a segmented architecture so that units of code can be fixed or updated on their own release schedule</li>
<li>an outlet for the core developers so that they don’t have to include every cool new feature under the sun</li>
</ul>
<p>After reading this guide you should be familiar with:</p>
<ul>
<li>Creating a plugin from scratch</li>
<li>Writing and running tests for the plugin</li>
<li>Storing models, views, controllers, helpers and even other plugins in your plugins</li>
<li>Writing generators</li>
<li>Writing custom Rake tasks in your plugin</li>
<li>Generating RDoc documentation for your plugin</li>
<li>Avoiding common pitfalls with ‘init.rb’</li>
</ul>
<p>This guide describes how to build a test-driven plugin that will:</p>
<ul>
<li>Extend core ruby classes like Hash and String</li>
<li>Add methods to ActiveRecord::Base in the tradition of the ‘acts_as’ plugins</li>
<li>Add a view helper that can be used in erb templates</li>
<li>Add a new generator that will generate a migration</li>
<li>Add a custom generator command</li>
<li>A custom route method that can be used in routes.rb</li>
</ul>
<p>For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.</p>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#setup">Setup</a><ul><li><a href="#create-the-basic-application">Create the Basic Application</a></li> <li><a href="#generate-the-plugin-skeleton">Generate the Plugin Skeleton</a></li> <li><a href="#organize-your-files">Organize Your Files</a></li></ul></li><li><a href="#tests">Tests</a><ul><li><a href="#test-setup">Test Setup</a></li> <li><a href="#run-the-plugin-tests">Run the Plugin Tests</a></li></ul></li><li><a href="#extending-core-classes">Extending Core Classes</a><ul><li><a href="#working-with-init-rb">Working with <tt>init.rb</tt></a></li></ul></li><li><a href="#add-an-acts_as-method-to-active-record">Add an “acts_as” Method to Active Record</a><ul><li><a href="#add-a-class-method">Add a Class Method</a></li> <li><a href="#add-an-instance-method">Add an Instance Method</a></li></ul></li><li><a href="#models">Models</a></li><li><a href="#controllers">Controllers</a></li><li><a href="#helpers">Helpers</a></li><li><a href="#routes">Routes</a></li><li><a href="#generators">Generators</a><ul><li><a href="#testing-generators">Testing Generators</a></li> <li><a href="#the-usage-file">The <tt>USAGE</tt> File</a></li></ul></li><li><a href="#add-a-custom-generator-command">Add a Custom Generator Command</a></li><li><a href="#generator-commands">Generator Commands</a></li><li><a href="#migrations">Migrations</a><ul><li><a href="#create-a-custom-rake-task">Create a Custom Rake Task</a></li> <li><a href="#call-migrations-directly">Call Migrations Directly</a></li> <li><a href="#generate-migrations">Generate Migrations</a></li></ul></li><li><a href="#rake-tasks">Rake Tasks</a></li><li><a href="#plugins-as-gems">Plugins as Gems</a></li><li><a href="#rdoc-documentation">RDoc Documentation</a></li><li><a href="#appendix">Appendix</a><ul><li><a href="#references">References</a></li> <li><a href="#contents-of-lib-yaffle-rb">Contents of <tt>lib/yaffle.rb</tt></a></li> <li><a href="#final-plugin-directory-structure">Final Plugin Directory Structure</a></li></ul></li><li><a href="#changelog">Changelog</a></li></ol></div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="setup">1 Setup</h3>
<h4 id="create-the-basic-application">1.1 Create the Basic Application</h4>
<p>The examples in this guide require that you have a working rails application. To create a simple one execute:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
gem install rails
rails new yaffle_guide
cd yaffle_guide
bundle install
rails generate scaffold bird name:string
rake db:migrate
rails server
</pre>
</div>
</notextile>
<p>Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails application before continuing.</p>
<div class='note'><p>The aforementioned instructions will work for SQLite3. For more detailed instructions on how to create a Rails application for other databases see the <span class="caps">API</span> docs.</p></div>
<h4 id="generate-the-plugin-skeleton">1.2 Generate the Plugin Skeleton</h4>
<p>Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either ‘CamelCased’ or ‘under_scored’, as an argument. Pass <tt>--generator</tt> to add an example generator also.</p>
<p>This creates a plugin in <tt>vendor/plugins</tt> including an <tt>init.rb</tt> and <tt>README</tt> as well as standard <tt>lib</tt>, <tt>task</tt>, and <tt>test</tt> directories.</p>
<p>Examples:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
rails generate plugin yaffle
rails generate plugin yaffle --generator
</pre>
</div>
</notextile>
<p>To get more detailed help on the plugin generator, type <tt>rails generate plugin</tt>.</p>
<p>Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the <tt>--generator</tt> option now:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
rails generate plugin yaffle --generator
</pre>
</div>
</notextile>
<p>You should see the following output:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
create vendor/plugins/yaffle
create vendor/plugins/yaffle/init.rb
create vendor/plugins/yaffle/install.rb
create vendor/plugins/yaffle/MIT-LICENSE
create vendor/plugins/yaffle/Rakefile
create vendor/plugins/yaffle/README
create vendor/plugins/yaffle/uninstall.rb
create vendor/plugins/yaffle/lib
create vendor/plugins/yaffle/lib/yaffle.rb
invoke generator
inside vendor/plugins/yaffle
create lib/generators
create lib/generators/yaffle_generator.rb
create lib/generators/USAGE
create lib/generators/templates
invoke test_unit
inside vendor/plugins/yaffle
create test
create test/yaffle_test.rb
create test/test_helper.rb
</pre>
</div>
</notextile>
<h4 id="organize-your-files">1.3 Organize Your Files</h4>
<p>To make it easy to organize your files and to make the plugin more compatible with GemPlugins, start out by altering your file system to look like this:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
|-- lib
| |-- yaffle
| `-- yaffle.rb
`-- init.rb
</pre>
</div>
</notextile>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# vendor/plugins/yaffle/init.rb
require 'yaffle'
</pre>
</div>
</notextile>
<p>Now you can add any <tt>require</tt> statements to <tt>lib/yaffle.rb</tt> and keep <tt>init.rb</tt> clean.</p>
<h3 id="tests">2 Tests</h3>
<p>In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you’ll need to add 3 files:</p>
<ul>
<li>A <tt>database.yml</tt> file with all of your connection strings</li>
<li>A <tt>schema.rb</tt> file with your table definitions</li>
<li>A test helper method that sets up the database</li>
</ul>
<h4 id="test-setup">2.1 Test Setup</h4>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
# vendor/plugins/yaffle/test/database.yml
sqlite:
adapter: sqlite
database: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db
sqlite3:
adapter: sqlite3
database: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db
postgresql:
adapter: postgresql
username: postgres
password: postgres
database: yaffle_plugin_test
min_messages: ERROR
mysql:
adapter: mysql2
host: localhost
username: root
password: password
database: yaffle_plugin_test
</pre>
</div>
</notextile>
<p>For this guide you’ll need 2 tables/models, Hickwalls and Wickwalls, so add the following:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# vendor/plugins/yaffle/test/schema.rb
ActiveRecord::Schema.define(:version => 0) do
create_table :hickwalls, :force => true do |t|
t.string :name
t.string :last_squawk
t.datetime :last_squawked_at
end
create_table :wickwalls, :force => true do |t|
t.string :name
t.string :last_tweet
t.datetime :last_tweeted_at
end
create_table :woodpeckers, :force => true do |t|
t.string :name
end
end
</pre>
</div>
</notextile>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# vendor/plugins/yaffle/test/test_helper.rb
ENV['RAILS_ENV'] = 'test'
ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
require 'test/unit'
require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
def load_schema
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
db_adapter = ENV['DB']
# no db passed, try one of these fine config-free DBs before bombing.
db_adapter ||=
begin
require 'rubygems'
require 'sqlite'
'sqlite'
rescue MissingSourceFile
begin
require 'sqlite3'
'sqlite3'
rescue MissingSourceFile
end
end
if db_adapter.nil?
raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
end
ActiveRecord::Base.establish_connection(config[db_adapter])
load(File.dirname(__FILE__) + "/schema.rb")
require File.dirname(__FILE__) + '/../init'
end
</pre>
</div>
</notextile>
<p>Now whenever you write a test that requires the database, you can call ‘load_schema’.</p>
<h4 id="run-the-plugin-tests">2.2 Run the Plugin Tests</h4>
<p>Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in <tt>vendor/plugins/yaffle/test/yaffle_test.rb</tt> with a sample test. Replace the contents of that file with:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# vendor/plugins/yaffle/test/yaffle_test.rb
require 'test_helper'
class YaffleTest < ActiveSupport::TestCase
load_schema
class Hickwall < ActiveRecord::Base
end
class Wickwall < ActiveRecord::Base
end
def test_schema_has_loaded_correctly
assert_equal [], Hickwall.all
assert_equal [], Wickwall.all
end
end
</pre>
</div>
</notextile>
<p>To run this, go to the plugin directory and run <tt>rake</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
cd vendor/plugins/yaffle
rake
</pre>
</div>
</notextile>
<p>You should see output like:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb"
create_table(:hickwalls, {:force=>true})
-> 0.0220s
-- create_table(:wickwalls, {:force=>true})
-> 0.0077s
-- create_table(:woodpeckers, {:force=>true})
-> 0.0069s
-- initialize_schema_migrations_table()
-> 0.0007s
-- assume_migrated_upto_version(0, "db/migrate")
-> 0.0007s
Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
Started
.
Finished in 0.002236 seconds.
1 test, 2 assertion, 0 failures, 0 errors, 0 skips
</pre>
</div>
</notextile>
<p>By default the setup above runs your tests with SQLite or SQLite3. To run tests with one of the other connection strings specified in <tt>database.yml</tt>, pass the DB environment variable to rake:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
rake DB=sqlite
rake DB=sqlite3
rake DB=mysql
rake DB=postgresql
</pre>
</div>
</notextile>
<p>Now you are ready to test-drive your plugin!</p>
<h3 id="extending-core-classes">3 Extending Core Classes</h3>
<p>This section will explain how to add a method to String that will be available anywhere in your Rails application.</p>
<p>In this example you will add a method to String named <tt>to_squawk</tt>. To begin, create a new test file with a few assertions:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# vendor/plugins/yaffle/test/core_ext_test.rb
require File.dirname(__FILE__) + '/test_helper'
class CoreExtTest < Test::Unit::TestCase
def test_to_squawk_prepends_the_word_squawk
assert_equal "squawk! Hello World", "Hello World".to_squawk
end
end
</pre>
</div>
</notextile>
<p>Navigate to your plugin directory and run <tt>rake test</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
cd vendor/plugins/yaffle
rake test
</pre>
</div>
</notextile>
<p>The test above should fail with the message:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
1) Error:
test_to_squawk_prepends_the_word_squawk(CoreExtTest):
NoMethodError: undefined method `to_squawk' for "Hello World":String
./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'
</pre>
</div>
</notextile>
<p>Great – now you are ready to start development.</p>
<p>Then in <tt>lib/yaffle.rb</tt> require <tt>lib/core_ext</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# vendor/plugins/yaffle/lib/yaffle.rb
require "yaffle/core_ext"
</pre>
</div>
</notextile>
<p>Finally, create the <tt>core_ext.rb</tt> file and add the <tt>to_squawk</tt> method:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# vendor/plugins/yaffle/lib/yaffle/core_ext.rb
String.class_eval do
def to_squawk
"squawk! #{self}".strip
end
end
</pre>
</div>
</notextile>
<p>To test that your method does what it says it does, run the unit tests with <tt>rake</tt> from your plugin directory. To see this in action, fire up a console and start squawking:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails console
>> "Hello World".to_squawk
=> "squawk! Hello World"
</pre>
</div>
</notextile>
<h4 id="working-with-init-rb">3.1 Working with <tt>init.rb</tt></h4>
<p>When Rails loads plugins it looks for a file named <tt>init.rb</tt>. However, when the plugin is initialized, <tt>init.rb</tt> is invoked via <tt>eval</tt> (not <tt>require</tt>) so it has slightly different behavior.</p>
<div class='note'><p>The plugins loader also looks for <tt>rails/init.rb</tt>, but that one is deprecated in favor of the top-level <tt>init.rb</tt> aforementioned.</p></div>
<p>Under certain circumstances if you reopen classes or modules in <tt>init.rb</tt> you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from <tt>init.rb</tt>, as shown above.</p>
<p>If you must reopen a class in <tt>init.rb</tt> you can use <tt>module_eval</tt> or <tt>class_eval</tt> to avoid any issues:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# vendor/plugins/yaffle/init.rb
Hash.class_eval do
def is_a_special_hash?
true
end
end
</pre>
</div>
</notextile>
<p>Another way is to explicitly define the top-level module space for all modules and classes, like <tt>::Hash</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# vendor/plugins/yaffle/init.rb
class ::Hash
def is_a_special_hash?
true
end
end
</pre>
</div>
</notextile>
<h3 id="add-an-acts_as-method-to-active-record">4 Add an “acts_as” Method to Active Record</h3>
<p>A common pattern in plugins is to add a method called ‘acts_as_something’ to models. In this case, you want to write a method called ‘acts_as_yaffle’ that adds a ‘squawk’ method to your models.</p>
<p>To begin, set up your files so that you have:</p>
<ul>
<li><strong>vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require File.dirname(__FILE__) + '/test_helper'
class ActsAsYaffleTest < Test::Unit::TestCase
end
</pre>
</div>
</notextile>
<ul>
<li><strong>vendor/plugins/yaffle/lib/yaffle.rb</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'yaffle/acts_as_yaffle'
</pre>
</div>
</notextile>
<ul>
<li><strong>vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module Yaffle
# your code will go here
end
</pre>
</div>
</notextile>
<p>Note that after requiring ‘acts_as_yaffle’ you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models.</p>
<p>One of the most common plugin patterns for ‘acts_as_yaffle’ plugins is to structure your file like so:</p>
<ul>
<li><strong>vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
# any method placed here will apply to classes, like Hickwall
def acts_as_something
send :include, InstanceMethods
end
end
module InstanceMethods
# any method placed here will apply to instaces, like @hickwall
end
end
</pre>
</div>
</notextile>
<p>With structure you can easily separate the methods that will be used for the class (like <tt>Hickwall.some_method</tt>) and the instance (like <tt>@hickwell.some_method</tt>).</p>
<h4 id="add-a-class-method">4.1 Add a Class Method</h4>
<p>This plugin will expect that you’ve added a method to your model named ‘last_squawk’. However, the plugin users might have already defined a method on their model named ‘last_squawk’ that they use for something else. This plugin will allow the name to be changed by adding a class method called ‘yaffle_text_field’.</p>
<p>To start out, write a failing test that shows the behavior you’d like:</p>
<ul>
<li><strong>vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require File.dirname(__FILE__) + '/test_helper'
class Hickwall < ActiveRecord::Base
acts_as_yaffle
end
class Wickwall < ActiveRecord::Base
acts_as_yaffle :yaffle_text_field => :last_tweet
end
class ActsAsYaffleTest < Test::Unit::TestCase
load_schema
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
end
</pre>
</div>
</notextile>
<p>To make these tests pass, you could modify your <tt>acts_as_yaffle</tt> file like so:</p>
<ul>
<li><strong>vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def acts_as_yaffle(options = {})
cattr_accessor :yaffle_text_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
end
end
end
ActiveRecord::Base.send :include, Yaffle
</pre>
</div>
</notextile>
<h4 id="add-an-instance-method">4.2 Add an Instance Method</h4>
<p>This plugin will add a method named ‘squawk’ to any Active Record objects that call ‘acts_as_yaffle’. The ‘squawk’ method will simply set the value of one of the fields in the database.</p>
<p>To start out, write a failing test that shows the behavior you’d like:</p>
<ul>
<li><strong>vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require File.dirname(__FILE__) + '/test_helper'
class Hickwall < ActiveRecord::Base
acts_as_yaffle
end
class Wickwall < ActiveRecord::Base
acts_as_yaffle :yaffle_text_field => :last_tweet
end
class ActsAsYaffleTest < Test::Unit::TestCase
load_schema
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
def test_hickwalls_squawk_should_populate_last_squawk
hickwall = Hickwall.new
hickwall.squawk("Hello World")
assert_equal "squawk! Hello World", hickwall.last_squawk
end
def test_wickwalls_squawk_should_populate_last_tweeted_at
wickwall = Wickwall.new
wickwall.squawk("Hello World")
assert_equal "squawk! Hello World", wickwall.last_tweet
end
end
</pre>
</div>
</notextile>
<p>Run this test to make sure the last two tests fail, then update ‘acts_as_yaffle.rb’ to look like this:</p>
<ul>
<li><strong>vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def acts_as_yaffle(options = {})
cattr_accessor :yaffle_text_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
send :include, InstanceMethods
end
end
module InstanceMethods
def squawk(string)
write_attribute(self.class.yaffle_text_field, string.to_squawk)
end
end
end
ActiveRecord::Base.send :include, Yaffle
</pre>
</div>
</notextile>
<div class='note'><p>The use of <tt>write_attribute</tt> to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use <tt>send("#{self.class.yaffle_text_field}=", string.to_squawk)</tt>.</p></div>
<h3 id="models">5 Models</h3>
<p>This section describes how to add a model named ‘Woodpecker’ to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it’s customary to keep them in directories that match the rails directories. For this example, create a file structure like this:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
vendor/plugins/yaffle/
|-- lib
| |-- app
| | |-- controllers
| | |-- helpers
| | |-- models
| | | `-- woodpecker.rb
| | `-- views
| |-- yaffle
| | |-- acts_as_yaffle.rb
| | |-- commands.rb
| | `-- core_ext.rb
| `-- yaffle.rb
</pre>
</div>
</notextile>
<p>As always, start with a test:</p>
<ul>
<li><strong>vendor/plugins/yaffle/test/woodpecker_test.rb:</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require File.dirname(__FILE__) + '/test_helper'
class WoodpeckerTest < Test::Unit::TestCase
load_schema
def test_woodpecker
assert_kind_of Woodpecker, Woodpecker.new
end
end
</pre>
</div>
</notextile>
<p>This is just a simple test to make sure the class is being loaded correctly. After watching it fail with <tt>rake</tt>, you can make it pass like so:</p>
<ul>
<li><strong>vendor/plugins/yaffle/lib/yaffle.rb:</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
%w{ models }.each do |dir|
path = File.join(File.dirname(__FILE__), 'app', dir)
$LOAD_PATH << path
ActiveSupport::Dependencies.autoload_paths << path
ActiveSupport::Dependencies.autoload_once_paths.delete(path)
end
</pre>
</div>
</notextile>
<p>Adding directories to the load path makes them appear just like files in the main app directory – except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the ‘load_once_paths’ allow those changes to picked up as soon as you save the file – without having to restart the web server. This is particularly useful as you develop the plugin.</p>
<ul>
<li><strong>vendor/plugins/yaffle/lib/app/models/woodpecker.rb:</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Woodpecker < ActiveRecord::Base
end
</pre>
</div>
</notextile>
<p>Finally, add the following to your plugin’s ‘schema.rb’:</p>
<ul>
<li><strong>vendor/plugins/yaffle/test/schema.rb:</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
create_table :woodpeckers, :force => true do |t|
t.string :name
end
</pre>
</div>
</notextile>
<p>Now your test should be passing, and you should be able to use the Woodpecker model from within your rails application, and any changes made to it are reflected immediately when running in development mode.</p>
<h3 id="controllers">6 Controllers</h3>
<p>This section describes how to add a controller named ‘woodpeckers’ to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.</p>
<p>You can test your plugin’s controller as you would test any other controller:</p>
<ul>
<li><strong>vendor/plugins/yaffle/test/woodpeckers_controller_test.rb:</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require File.dirname(__FILE__) + '/test_helper'
require 'woodpeckers_controller'
require 'action_controller/test_process'
class WoodpeckersController; def rescue_action(e) raise e end; end
class WoodpeckersControllerTest < Test::Unit::TestCase
def setup
@controller = WoodpeckersController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
ActionController::Routing::Routes.draw do |map|
map.resources :woodpeckers
end
end
def test_index
get :index
assert_response :success
end
end
</pre>
</div>
</notextile>
<p>This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with <tt>rake</tt>, you can make it pass like so:</p>
<ul>
<li><strong>vendor/plugins/yaffle/lib/yaffle.rb:</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
%w{ models controllers }.each do |dir|
path = File.join(File.dirname(__FILE__), 'app', dir)
$LOAD_PATH << path
ActiveSupport::Dependencies.autoload_paths << path
ActiveSupport::Dependencies.autoload_once_paths.delete(path)
end
</pre>
</div>
</notextile>
<ul>
<li><strong>vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class WoodpeckersController < ActionController::Base
def index
render :text => "Squawk!"
end
end
</pre>
</div>
</notextile>
<p>Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action.</p>
<h3 id="helpers">7 Helpers</h3>
<p>This section describes how to add a helper named ‘WoodpeckersHelper’ to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.</p>
<p>You can test your plugin’s helper as you would test any other helper:</p>
<ul>
<li><strong>vendor/plugins/yaffle/test/woodpeckers_helper_test.rb</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require File.dirname(__FILE__) + '/test_helper'
include WoodpeckersHelper
class WoodpeckersHelperTest < Test::Unit::TestCase
def test_tweet
assert_equal "Tweet! Hello", tweet("Hello")
end
end
</pre>
</div>
</notextile>
<p>This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with <tt>rake</tt>, you can make it pass like so:</p>
<ul>
<li><strong>vendor/plugins/yaffle/lib/yaffle.rb:</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
%w{ models controllers helpers }.each do |dir|
path = File.join(File.dirname(__FILE__), 'app', dir)
$LOAD_PATH << path
ActiveSupport::Dependencies.autoload_paths << path
ActiveSupport::Dependencies.autoload_once_paths.delete(path)
end
</pre>
</div>
</notextile>
<ul>
<li><strong>vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module WoodpeckersHelper
def tweet(text)
"Tweet! #{text}"
end
end
</pre>
</div>
</notextile>
<p>Now your test should be passing, and you should be able to use the Woodpeckers helper in your app.</p>
<h3 id="routes">8 Routes</h3>
<p>You can add your own custom routes from a plugin. This section will describe how to add a custom method that can be called with ‘map.yaffles’.</p>
<p>Testing routes from plugins is slightly different from testing routes in a standard Rails application. To begin, add a test like this:</p>
<ul>
<li><strong>vendor/plugins/yaffle/test/routing_test.rb</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require "#{File.dirname(__FILE__)}/test_helper"
class RoutingTest < Test::Unit::TestCase
def setup
ActionController::Routing::Routes.draw do |map|
map.yaffles
end
end
def test_yaffles_route
assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index"
end
private
def assert_recognition(method, path, options)
result = ActionController::Routing::Routes.recognize_path(path, :method => method)
assert_equal options, result
end
end
</pre>
</div>
</notextile>
<p>Once you see the tests fail by running ‘rake’, you can make them pass with:</p>
<ul>
<li><strong>vendor/plugins/yaffle/lib/yaffle.rb</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require "yaffle/routing"
</pre>
</div>
</notextile>
<ul>
<li><strong>vendor/plugins/yaffle/lib/yaffle/routing.rb</strong></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module Yaffle #:nodoc:
module Routing #:nodoc:
module MapperExtensions
def yaffles
@set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"})
end