ActsAsPreferenced

ActsAsPreferenced helps with handling of some settings you might want to store per-object (usually per-user) in Rails applications. It provides unified API to access those, ways to handle default values and some useful view helpers. Preferences may be divided into sections for easier categorization if many are present.

Preferences can be stored in one of pluggable stores. Currently two stores are implemented: Field (stores in serialized db column) and Association (stores in associated table). One of the aims of this gem was to provide smooth transition between different stores - API stays the same for all of them, so you may start with preferences being stored in a serialized field and then transition to associated table.

Example

# Association store - use whatever association you like, there are just 2 # requirements: # * associated table needs to have field for every preference (type matching) # * the name of the association cannot be “preferences”, as it is used # internally by ActsAsPreferenced

class User attr_accessor :user_preferences

acts_as_preferenced( :association => :user_preferences ) do |config| # Just an integer preference with allowed range config.preference :items_per_page, :section => :general, :choices => (1..100), :default => 20 # Define the whole section of preferences. :prefix => true means # preference names will start with section name, so :flowers will become # “likes_flowers?” method (“?” added because it’s boolean) config.section :likes, :prefix => true do |section| section.preference :flowers, :default => true # No default - if not set will be nil section.preference :animals end # Enumerated preference with no section (it belongs to nil section) config.preference :likes_people, :choices => [:no, :little, :yes] end

end

OR

# Field store

class User acts_as_preferenced( :field => :prefs, … end

# Usage

user = User.new user.likes_flowers? # True - default; as preference is boolean question mark is appended to getter user.likes_flowers = false user.likes_flowers? # False user.likes_animals? # Nil - no default present user.items_per_page = 120 # ArgumentError - value out of range user.likes_people = :yes user.likes_people # :yes - name might be misleading, but it’s not boolean, so no question mark here

TODO

Helpers API documentation Migration generator for Association store. I18n tests.

Copyright © 2009-2013 Marek Janukowicz, released under the MIT license