Sha256: 9ad96c103479c7e1704f6148cb1cd2f31a68d2e1a40c0339744a253594a23d36

Contents?: true

Size: 1.41 KB

Versions: 1

Compression:

Stored size: 1.41 KB

Contents

module PluginAWeek #:nodoc:
  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.
      # This uses ActiveRecord's typecast functionality so the same rules for
      # typecasting a model's columns apply here.
      def type_cast(value)
        @type == 'any' ? value : @column.type_cast(value)
      end
      
      # Typecasts the value to true/false depending on the type of preference
      def query(value)
        if !(value = type_cast(value))
          false
        elsif @column.number?
          !value.zero?
        else
          !value.blank?
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
preferences-0.1.5 lib/preferences/preference_definition.rb