Modularity provides traits and partial classes for Ruby. This allows very simple definition of meta-programming macros, as you might now from acts_as_something
type of plugins, or the macros Rails provides for your models. This also lets you organize large models into multiple source files in a way that is less awkward than using modules.
Modularity traits are to your models what partials are for your Rails views.
Ruby allows you to construct classes using meta-programming macros like acts_as_tree
or has_many :items
. These macros will add methods, callbacks, etc. to the calling class. However, right now Ruby (and Rails) makes it awkward to define such macros in your project as part of your application domain.
Modularity allows you to extract common behaviour into reusable macros by defining traits with parameters. Your macros can live in your application, allowing you to express your application domain in both classes and macros.
Here is an example of a strip_field
macro, which created setter methods that remove leading and trailing whitespace from newly assigned values:
# app/models/article.rb class Article does "strip_fields", :name, :brand end # app/models/shared/strip_fields_trait.rb module StripFieldsTrait as_trait do |*fields| fields.each do |field| define_method("#{field}=") do |value| self[field] = value.strip end end end end
We like to add app/models/shared
and app/controllers/shared
to the load paths of our Rails projects. These are great places to store macros that are re-used from multiple classes.
Using a module to add both instance methods and class methods is very awkward. Modularity does away with the clutter and lets you say this:
# app/models/model.rb class Model does "mixin" end # app/models/mixin_trait.rb module MixinTrait as_trait do def instance_method # ... end def self.class_method # .. end end
private
and protected
will also work as expected when defining a trait.
Models are often concerned with multiple themes like “authentication”, “contact info” or “permissions”, each requiring a couple of validations and callbacks here, and some method there. Modularity lets you organize your model into multiple partial classes, so each file can deal with a single aspect of your model:
# app/models/user.rb class User < ActiveRecord::Base does "user/authentication" does "user/address" end # app/models/user/authentication_trait.rb module User::AuthenticationTrait as_trait do # methods, validations, etc. regarding usernames and passwords go here end end # app/models/user/permissions_trait.rb module User::PermissionsTrait as_trait do # methods, validations, etc. regarding contact information go here end end
sudo gem install modularity
Modularity requires Ruby 1.8.7. Earlier versions are missing class_exec
. You might be able to hack in class_exec
using this as a guide, but it’s not pretty.
Henning Koch