Latest Comment by Ben ~ Thu Jan 28 on Git stash

Rails plugin: acts_as_configurable

Disclaimer: this is based off of Chris’ configuration he posted about a year ago. Hopefully he doesn’t mind :-)

With his version, he focused on application-wide configuration settings. I’ve wrapped it up in a plugin and modified it so that you can have configuration exclusive to any Ruby class. I guess one could say it’s a nicer way to deal with constants.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class API
  acts_as_configurable

  configuration do |config|
    config.flickr do |f|
      f.key = '123456'
      f.cache_filename = 'flickr_cache'
    end

    config.delicious do |d|
      d.username = 'username'
      d.password = 'password'
      d.cache_filename = 'delicious_cache'
    end
  end
end

Now I can keep all of my API configuration within the API class, without the bulk of long-winded constants. Plus, getting at the data is a lot nicer.

1
2
3
4
5
6
$> API.flickr
# => { :key => '123456', :cache_filename => 'flickr_cache' }
$> API.flickr.key
# => '123456'
$> API.delicious.username
# => 'username'

I realize that “configuration” has the potential to clash with a class method already present in your code. To get around that, the configuration method is also configurable.

1
2
3
4
5
6
7
8
9
class API
  acts_as_configurable :with => :settings

  settings do |setting|
    setting.flickr do |f|
      # ...
    end
  end
end

Then you’d just replace “configuration” with “settings” when you want to get the data back.

1
2
$> API.settings.flickr
# => { :key => '123456', :cache_filename => 'flickr_cache' }

You can find it on GitHub.

Comments

01

Chris on Tue Oct 28 at 05:14PM

Code thief! Thanks for wrapping this up as a plugin, though :)

02

Ryan on Tue Oct 28 at 05:39PM

Honestly, I’ve been porting it from project to project manually, and it got old. All I needed was a little boost of motivation.

Oh, and I highlighted the disclaimer at the top of this post to make it stand out more. And it’s also in the code comments.

(Just trying to make myself feel better about stealing your code!)

Have something to say?
Protected by Defensio Formatting Tips

or

Copyright © 2010 Ryan Heath | Site Management A Ruby on Rails production.

This site is a Formed Function. Formed Function LLC | @formedfunction | Get in Touch