a DRYer way to include modules

You may have noticed in the previous post that we used the RMobio ads module merely by doing “require rmobio/ads” inside our controller class. This is terser than and less repetitive (in the spirit of Don’t Repeat Yourself) than doing a require followed by doing an include inside the module.

The code inside the module to allow this is

if MOBIO_CONFIG['ad_network']
  adlib="rmobio/ads/" + MOBIO_CONFIG['ad_network']
  adlib='rmobio/ads/' + 'no_network'
require adlib
eval("include " + adlib.camelize)

What this does is build up the specific class for the ad_network that is configured in the generic RMobio configuration file (RMobio.yml). If no ad network is configured, we still want to have calls to getAd and getAdByPage not fail. So there is a module called no_network.rb with those calls stubbed out.

We then do the require of whatever ad library is chosen. Finally we generate the code dynamically (using “eval”) to do the include of the module name (using the handy camelize function to get the module name from the filename). This generic technique of dynamically determining the right module to include can make your code a briefer and terser. We use it in the RMobio gem and I’m hoping it catches on wider in the Ruby community.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: