Sha256: fe1dd0500535a100d8a11a7864ba7e01086e01f804c70f21d05f04e87ebfb762

Contents?: true

Size: 1.31 KB

Versions: 40

Compression:

Stored size: 1.31 KB

Contents

# encoding: UTF-8
module MongoMapper
  module Plugins
    module Keys
      class Key
        attr_accessor :name, :type, :options, :default_value

        def initialize(*args)
          options = args.extract_options!
          @name, @type = args.shift.to_s, args.shift
          self.options = (options || {}).symbolize_keys
          self.default_value = self.options[:default]
        end

        def ==(other)
          @name == other.name && @type == other.type
        end

        def embeddable?
          return false unless type.respond_to?(:embeddable?)
          type.embeddable?
        end

        def number?
          [Integer, Float].include?(type)
        end

        def get(value)
          if value.nil? && !default_value.nil?
            if default_value.respond_to?(:call)
              return default_value.call
            else
              return default_value
            end
          end

          type.from_mongo(value)
        end

        def set(value)
          type.to_mongo(value).tap do |values|
            if options[:typecast].present?
              values.map! { |v| typecast_class.to_mongo(v) }
            end
          end
        end
        
        private
          def typecast_class
            @typecast_class ||= options[:typecast].constantize
          end
      end
    end
  end
end

Version data entries

40 entries across 40 versions & 3 rubygems

Version Path
mongo_mapper-unstable-2010.08.08 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.08.06 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.08.05 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.08.04 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.08.03 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.08.02 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.08.01 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.07.31 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.07.30 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.07.29 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.07.28 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.07.27 lib/mongo_mapper/plugins/keys/key.rb
thorsson-mongo_mapper-0.8.2 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.07.26 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.07.23 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.07.21 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.07.20 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.07.19 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.07.18 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-unstable-2010.07.16 lib/mongo_mapper/plugins/keys/key.rb