litany against fear

coding with spice ¤ by nick quaranto

Demystifying Rails Plugin Development Notes

published 18 Nov 2008

Part of my series of notes from the Professional Ruby Conference. See them all here.

This talk is from Nick Plante.

Work more on the ‘special sauce’ of Rails. Plugins can save you a LOT of time! Generalized, reusable code libraries. Lets us mold the Rails framework into what we want it to be and make it more powerful. It’s a lot easier than you think! Some examples: User authentication, Pagination, Asychronous Processing, View Helpers.

Why develop them? Internal reuse, opportunity to refactor & clean up. Also contributes to the Ruby OSS ecosystem! Most plugins don’t start as plugins. They really shouldn’t…they’re extracted/generalized.

Nick is going over an example of making a plugin for validating ISBN numbers. Lots of messy code lives in the model…it can hit a limit. Extract it! Use encapsulation and information hiding…Extract into /lib, or better yet, make a plugin!

When designing the interface for a plugin, KISS. Extend the Rails DSL in a natural way…many pre-existing examples to guide us (ActiveRecord::Validations in this case). Showing some examples of plugins, from Paperclip, acts_as_list, some for ActionController and ActionView too.

Make people learn as LITTLE new stuff as possible to use your plugin. Showing off an example module for the ISBN validation. Some methods I haven’t seen before: extract_options! validates_each

Why is it a module and not a class? A module is a degenerate abstract class and can be mixed into a class. Include for instance methods, extend for class methods.

Plugin hooks! Install.rb: Auto-run when the plugin is installed with script/plugin install. Used to show the readme and copy any assets over. (Uninstall.rb for the opposite). Init.rb is used to inject plugin code into the framework, runs when the application is started. Common idiom is to use self.included to extend modules as well.

NEED TESTS. (TATFT!) If you’ve extracted it, you should have the tests. Right? Some strategies: mock/stub out the environment if possible. Rake tasks are generated for helping out with testing plugins too. RSpec also has a plugin generator.

Distributing plugins is super easy. Any old SVN/Git repo, RubyForge, GitHub. They can also be packaged as Gems and use the various rake tasks for gem installing/unpacking. Why use Gems? They have proper versioning and dependency management. GitHub makes creating gems super easy.

Don’t be afraid! Read the Rails source too.



code (2) gaming (3) git (9) internet (5) prorubyconf (25) railsconf (17) ruby (10) windows (3)