Skip to content

Instantly share code, notes, and snippets.

@ivanvanderbyl
Created December 1, 2009 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivanvanderbyl/246728 to your computer and use it in GitHub Desktop.
Save ivanvanderbyl/246728 to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
serialize :preferences
def method_missing(method_name, *arguments)
pref_match_setter = method_name.to_s.match(/^pref_(.+)\=$/)
pref_match_getter = method_name.to_s.match(/^pref_(.+)$/)
if pref_match_setter
current_prefs = self.preferences && self.preferences.any? && self.preferences || {}
current_prefs.merge!(pref_match_setter.to_a.last.to_s => arguments[0])
self.write_attribute(:preferences, current_prefs)
elsif pref_match_getter
self.preferences[pref_match_getter.to_a.last.to_s]
else
super
end
end
end
# user = User.find(612)
#
# >> user.pref_email_notification
# => nil
# >> user.pref_email_notification = 1
# => 1
# >> user.pref_email_notification
# => 1
# >> user.preferences
# => {"email_notification"=>1}
# >> user.save
# => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment