PageRenderTime 60ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/guides/source/plugins.md

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