Sha256: cd00fc77b0198d407ee2f05d9ffd2c48c0d21fe0f7984b70ba7330d988b478f5

Contents?: true

Size: 1.42 KB

Versions: 5

Compression:

Stored size: 1.42 KB

Contents

module PluginAWeek #:nodoc:
  # Adds support for defining preferences on ActiveRecord models.
  module Preferences
    # Represents the definition of a preference for a particular model
    class PreferenceDefinition
      def initialize(attribute, *args) #:nodoc:
        options = args.extract_options!
        options.assert_valid_keys(:default)
        
        @type = args.first ? args.first.to_s : 'boolean'
        
        # Create a column that will be responsible for typecasting
        @column = ActiveRecord::ConnectionAdapters::Column.new(attribute.to_s, options[:default], @type == 'any' ? nil : @type)
      end
      
      # The attribute which is being preferenced
      def attribute
        @column.name
      end
      
      # The default value to use for the preference in case none have been
      # previously defined      
      def default_value
        @column.default
      end
      
      # Typecasts the value based on the type of preference that was defined
      def type_cast(value)
        if @type == 'any'
          value
        else
          @column.type_cast(value)
        end
      end
      
      # Typecasts the value to true/false depending on the type of preference
      def query(value)
        unless value = type_cast(value)
          false
        else
          if @column.number?
            !value.zero?
          else
            !value.blank?
          end
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
preferences-0.0.1 lib/preferences/preference_definition.rb
preferences-0.1.0 lib/preferences/preference_definition.rb
preferences-0.1.1 lib/preferences/preference_definition.rb
preferences-0.1.2 lib/preferences/preference_definition.rb
preferences-0.1.3 lib/preferences/preference_definition.rb