plugins.textile 14 KB

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