Rails: Extending Classes, Creating Mixins

Posted on February 6, 2007
Filed Under /dev/ruby | 4,534 views |

I tend towards disliking the use of inheritance with my own objects. It's great for components in frameworks where I only have to worry about the end product but in my own code I default towards thinking of inheritance as a flaw and only concede when no other alternative is as elegant.

Which is why I'm really liking Ruby's concept of mixins. It's like using an interface, with none of the ugly. Kind'a.

A little gotcha with them though, depending on how you want to call the extending functions. If you want to access them through an instance variable, you need to include the extending module via include:

RUBY:
  1. class User
  2.   include PasswordHelper
  3.   ...
  4. end

RUBY:
  1. user = User.new()
  2. user.change_password( new_password )

If you want to access them as class methods you need to include the extending module via extend:

RUBY:
  1. class User
  2.   extend PasswordHelper
  3.   ...
  4. end

RUBY:
  1. all_password = User.get_all_passwords

(That's a terrible example but you get the point. At least, I get the point.)

I do find the difference in syntax for require and include/extend a little odd though:

RUBY:
  1. class User
  2.   require 'Authenticator'
  3.   extend PasswordHelper
  4. end

Note the quotes.

Comments

Comments are closed.