Sha256: 4b0a17a926d917e81b675655329c5afebb315e92aa7fa8a11e23537723327de2

Contents?: true

Size: 957 Bytes

Versions: 1

Compression:

Stored size: 957 Bytes

Contents

require 'active_support/concern'

module Flavors
  module Preferences
    extend ::ActiveSupport::Concern

    module ClassMethods
      def preference(name, options = {}, &callback)
        has_many :preferences, :as => :prefered, :class_name => "::Flavors::Preference"

        define_method(name) do
          read_preference(name, options[:default])
        end

        define_method("#{name}?") do
          read_preference(name, options[:default])
        end

        define_method("#{name}=") do |value|
          write_preference(name, value)
          callback.call(self, value) if callback
        end
      end
    end

    def read_preference(name, default = nil)
      if p = self.preferences.where(:name => name).first
        p.value
      else
        default
      end
    end

    def write_preference(name, value)
      p = self.preferences.where(:name => name).first_or_create
      p.update_attribute(:value, value)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
flavors-0.5.0 lib/flavors/preferences/preferences.rb