/guides/source/plugins.md
Markdown | 484 lines | 330 code | 154 blank | 0 comment | 0 complexity | 54f45132e27070dc92129e7d2d7f97e6 MD5 | raw file
1**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**
2
3The Basics of Creating Rails Plugins
4====================================
5
6A Rails plugin is either an extension or a modification of the core framework. Plugins provide:
7
8* A way for developers to share bleeding-edge ideas without hurting the stable code base.
9* A segmented architecture so that units of code can be fixed or updated on their own release schedule.
10* An outlet for the core developers so that they don't have to include every cool new feature under the sun.
11
12After reading this guide, you will know:
13
14* How to create a plugin from scratch.
15* How to write and run tests for the plugin.
16
17This guide describes how to build a test-driven plugin that will:
18
19* Extend core Ruby classes like Hash and String.
20* Add methods to `ApplicationRecord` in the tradition of the `acts_as` plugins.
21* Give you information about where to put generators in your plugin.
22
23For the purpose of this guide pretend for a moment that you are an avid bird watcher.
24Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle
25goodness.
26
27--------------------------------------------------------------------------------
28
29Setup
30-----
31
32Currently, Rails plugins are built as gems, _gemified plugins_. They can be shared across
33different Rails applications using RubyGems and Bundler if desired.
34
35### Generate a gemified plugin.
36
37
38Rails ships with a `rails plugin new` command which creates a
39skeleton for developing any kind of Rails extension with the ability
40to run integration tests using a dummy Rails application. Create your
41plugin with the command:
42
43```bash
44$ rails plugin new yaffle
45```
46
47See usage and options by asking for help:
48
49```bash
50$ rails plugin new --help
51```
52
53Testing Your Newly Generated Plugin
54-----------------------------------
55
56You can navigate to the directory that contains the plugin, run the `bundle install` command
57 and run the one generated test using the `bin/test` command.
58
59You should see:
60
61```bash
62 1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
63```
64
65This will tell you that everything got generated properly and you are ready to start adding functionality.
66
67Extending Core Classes
68----------------------
69
70This section will explain how to add a method to String that will be available anywhere in your Rails application.
71
72In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions:
73
74```ruby
75# yaffle/test/core_ext_test.rb
76
77require "test_helper"
78
79class CoreExtTest < ActiveSupport::TestCase
80 def test_to_squawk_prepends_the_word_squawk
81 assert_equal "squawk! Hello World", "Hello World".to_squawk
82 end
83end
84```
85
86Run `bin/test` to run the test. This test should fail because we haven't implemented the `to_squawk` method:
87
88```bash
89E
90
91Error:
92CoreExtTest#test_to_squawk_prepends_the_word_squawk:
93NoMethodError: undefined method `to_squawk' for "Hello World":String
94
95
96bin/test /path/to/yaffle/test/core_ext_test.rb:4
97
98.
99
100Finished in 0.003358s, 595.6483 runs/s, 297.8242 assertions/s.
101
1022 runs, 1 assertions, 0 failures, 1 errors, 0 skips
103```
104
105Great - now you are ready to start development.
106
107In `lib/yaffle.rb`, add `require "yaffle/core_ext"`:
108
109```ruby
110# yaffle/lib/yaffle.rb
111
112require "yaffle/railtie"
113require "yaffle/core_ext"
114
115module Yaffle
116 # Your code goes here...
117end
118```
119
120Finally, create the `core_ext.rb` file and add the `to_squawk` method:
121
122```ruby
123# yaffle/lib/yaffle/core_ext.rb
124
125class String
126 def to_squawk
127 "squawk! #{self}".strip
128 end
129end
130```
131
132To test that your method does what it says it does, run the unit tests with `bin/test` from your plugin directory.
133
134```bash
135 2 runs, 2 assertions, 0 failures, 0 errors, 0 skips
136```
137
138To see this in action, change to the `test/dummy` directory, fire up a console, and start squawking:
139
140```bash
141$ rails console
142>> "Hello World".to_squawk
143=> "squawk! Hello World"
144```
145
146Add an "acts_as" Method to Active Record
147----------------------------------------
148
149A common pattern in plugins is to add a method called `acts_as_something` to models. In this case, you
150want to write a method called `acts_as_yaffle` that adds a `squawk` method to your Active Record models.
151
152To begin, set up your files so that you have:
153
154```ruby
155# yaffle/test/acts_as_yaffle_test.rb
156
157require "test_helper"
158
159class ActsAsYaffleTest < ActiveSupport::TestCase
160end
161```
162
163```ruby
164# yaffle/lib/yaffle.rb
165
166require "yaffle/railtie"
167require "yaffle/core_ext"
168require "yaffle/acts_as_yaffle"
169
170module Yaffle
171 # Your code goes here...
172end
173```
174
175```ruby
176# yaffle/lib/yaffle/acts_as_yaffle.rb
177
178module Yaffle
179 module ActsAsYaffle
180 end
181end
182```
183
184### Add a Class Method
185
186This plugin will expect that you've added a method to your model named `last_squawk`. However, the
187plugin users might have already defined a method on their model named `last_squawk` that they use
188for something else. This plugin will allow the name to be changed by adding a class method called `yaffle_text_field`.
189
190To start out, write a failing test that shows the behavior you'd like:
191
192```ruby
193# yaffle/test/acts_as_yaffle_test.rb
194
195require "test_helper"
196
197class ActsAsYaffleTest < ActiveSupport::TestCase
198 def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
199 assert_equal "last_squawk", Hickwall.yaffle_text_field
200 end
201
202 def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
203 assert_equal "last_tweet", Wickwall.yaffle_text_field
204 end
205end
206```
207
208When you run `bin/test`, you should see the following:
209
210```
211# Running:
212
213..E
214
215Error:
216ActsAsYaffleTest#test_a_wickwalls_yaffle_text_field_should_be_last_tweet:
217NameError: uninitialized constant ActsAsYaffleTest::Wickwall
218
219
220bin/test /path/to/yaffle/test/acts_as_yaffle_test.rb:8
221
222E
223
224Error:
225ActsAsYaffleTest#test_a_hickwalls_yaffle_text_field_should_be_last_squawk:
226NameError: uninitialized constant ActsAsYaffleTest::Hickwall
227
228
229bin/test /path/to/yaffle/test/acts_as_yaffle_test.rb:4
230
231
232
233Finished in 0.004812s, 831.2949 runs/s, 415.6475 assertions/s.
234
2354 runs, 2 assertions, 0 failures, 2 errors, 0 skips
236```
237
238This tells us that we don't have the necessary models (Hickwall and Wickwall) that we are trying to test.
239We can easily generate these models in our "dummy" Rails application by running the following commands from the
240`test/dummy` directory:
241
242```bash
243$ cd test/dummy
244$ rails generate model Hickwall last_squawk:string
245$ rails generate model Wickwall last_squawk:string last_tweet:string
246```
247
248Now you can create the necessary database tables in your testing database by navigating to your dummy app
249and migrating the database. First, run:
250
251```bash
252$ cd test/dummy
253$ rails db:migrate
254```
255
256While you are here, change the Hickwall and Wickwall models so that they know that they are supposed to act
257like yaffles.
258
259```ruby
260# test/dummy/app/models/hickwall.rb
261
262class Hickwall < ApplicationRecord
263 acts_as_yaffle
264end
265
266# test/dummy/app/models/wickwall.rb
267
268class Wickwall < ApplicationRecord
269 acts_as_yaffle yaffle_text_field: :last_tweet
270end
271```
272
273We will also add code to define the `acts_as_yaffle` method.
274
275```ruby
276# yaffle/lib/yaffle/acts_as_yaffle.rb
277
278module Yaffle
279 module ActsAsYaffle
280 extend ActiveSupport::Concern
281
282 class_methods do
283 def acts_as_yaffle(options = {})
284 end
285 end
286 end
287end
288
289# test/dummy/app/models/application_record.rb
290
291class ApplicationRecord < ActiveRecord::Base
292 include Yaffle::ActsAsYaffle
293
294 self.abstract_class = true
295end
296```
297
298You can then return to the root directory (`cd ../..`) of your plugin and rerun the tests using `bin/test`.
299
300```
301# Running:
302
303.E
304
305Error:
306ActsAsYaffleTest#test_a_hickwalls_yaffle_text_field_should_be_last_squawk:
307NoMethodError: undefined method `yaffle_text_field' for #<Class:0x0055974ebbe9d8>
308
309
310bin/test /path/to/yaffle/test/acts_as_yaffle_test.rb:4
311
312E
313
314Error:
315ActsAsYaffleTest#test_a_wickwalls_yaffle_text_field_should_be_last_tweet:
316NoMethodError: undefined method `yaffle_text_field' for #<Class:0x0055974eb8cfc8>
317
318
319bin/test /path/to/yaffle/test/acts_as_yaffle_test.rb:8
320
321.
322
323Finished in 0.008263s, 484.0999 runs/s, 242.0500 assertions/s.
324
3254 runs, 2 assertions, 0 failures, 2 errors, 0 skips
326```
327
328Getting closer... Now we will implement the code of the `acts_as_yaffle` method to make the tests pass.
329
330```ruby
331# yaffle/lib/yaffle/acts_as_yaffle.rb
332
333module Yaffle
334 module ActsAsYaffle
335 extend ActiveSupport::Concern
336
337 class_methods do
338 def acts_as_yaffle(options = {})
339 cattr_accessor :yaffle_text_field, default: (options[:yaffle_text_field] || :last_squawk).to_s
340 end
341 end
342 end
343end
344
345# test/dummy/app/models/application_record.rb
346
347class ApplicationRecord < ActiveRecord::Base
348 include Yaffle::ActsAsYaffle
349
350 self.abstract_class = true
351end
352```
353
354When you run `bin/test`, you should see the tests all pass:
355
356```bash
357 4 runs, 4 assertions, 0 failures, 0 errors, 0 skips
358```
359
360### Add an Instance Method
361
362This plugin will add a method named 'squawk' to any Active Record object that calls `acts_as_yaffle`. The 'squawk'
363method will simply set the value of one of the fields in the database.
364
365To start out, write a failing test that shows the behavior you'd like:
366
367```ruby
368# yaffle/test/acts_as_yaffle_test.rb
369require "test_helper"
370
371class ActsAsYaffleTest < ActiveSupport::TestCase
372 def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
373 assert_equal "last_squawk", Hickwall.yaffle_text_field
374 end
375
376 def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
377 assert_equal "last_tweet", Wickwall.yaffle_text_field
378 end
379
380 def test_hickwalls_squawk_should_populate_last_squawk
381 hickwall = Hickwall.new
382 hickwall.squawk("Hello World")
383 assert_equal "squawk! Hello World", hickwall.last_squawk
384 end
385
386 def test_wickwalls_squawk_should_populate_last_tweet
387 wickwall = Wickwall.new
388 wickwall.squawk("Hello World")
389 assert_equal "squawk! Hello World", wickwall.last_tweet
390 end
391end
392```
393
394Run the test to make sure the last two tests fail with an error that contains "NoMethodError: undefined method `squawk'",
395then update `acts_as_yaffle.rb` to look like this:
396
397```ruby
398# yaffle/lib/yaffle/acts_as_yaffle.rb
399
400module Yaffle
401 module ActsAsYaffle
402 extend ActiveSupport::Concern
403
404 included do
405 def squawk(string)
406 write_attribute(self.class.yaffle_text_field, string.to_squawk)
407 end
408 end
409
410 class_methods do
411 def acts_as_yaffle(options = {})
412 cattr_accessor :yaffle_text_field, default: (options[:yaffle_text_field] || :last_squawk).to_s
413 end
414 end
415 end
416end
417
418# test/dummy/app/models/application_record.rb
419
420class ApplicationRecord < ActiveRecord::Base
421 include Yaffle::ActsAsYaffle
422
423 self.abstract_class = true
424end
425```
426
427Run `bin/test` one final time and you should see:
428
429```
430 6 runs, 6 assertions, 0 failures, 0 errors, 0 skips
431```
432
433NOTE: The use of `write_attribute` 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:
434
435```ruby
436send("#{self.class.yaffle_text_field}=", string.to_squawk)
437```
438
439Generators
440----------
441
442Generators can be included in your gem simply by creating them in a `lib/generators` directory of your plugin. More information about
443the creation of generators can be found in the [Generators Guide](generators.html).
444
445Publishing Your Gem
446-------------------
447
448Gem plugins currently in development can easily be shared from any Git repository. To share the Yaffle gem with others, simply
449commit the code to a Git repository (like GitHub) and add a line to the `Gemfile` of the application in question:
450
451```ruby
452gem "yaffle", git: "https://github.com/rails/yaffle.git"
453```
454
455After running `bundle install`, your gem functionality will be available to the application.
456
457When the gem is ready to be shared as a formal release, it can be published to [RubyGems](https://rubygems.org).
458For more information about publishing gems to RubyGems, see: [Publishing your gem](https://guides.rubygems.org/publishing).
459
460RDoc Documentation
461------------------
462
463Once your plugin is stable and you are ready to deploy, do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.
464
465The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
466
467* Your name
468* How to install
469* How to add the functionality to the app (several examples of common use cases)
470* Warnings, gotchas or tips that might help users and save them time
471
472Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add `#:nodoc:` comments to those parts of the code that are not included in the public API.
473
474Once your comments are good to go, navigate to your plugin directory and run:
475
476```bash
477$ bundle exec rake rdoc
478```
479
480### References
481
482* [Developing a RubyGem using Bundler](https://github.com/radar/guides/blob/master/gem-development.md)
483* [Using .gemspecs as Intended](http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/)
484* [Gemspec Reference](https://guides.rubygems.org/specification-reference/)