PageRenderTime 27ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/guides/source/plugins.md

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