Sha256: b8c0d1ac30c189954e4caa35a5db1808e932f8645cdddb4f28cdfec1f52e8f15

Contents?: true

Size: 1.62 KB

Versions: 8

Compression:

Stored size: 1.62 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?
          type == Integer || type == Float
        end

        def get(value)
          if value.nil? && !default_value.nil?
            if default_value.respond_to?(:call)
              return default_value.call
            else
              # Using Marshal is easiest way to get a copy of mutable objects
              # without getting an error on immutable objects
              return Marshal.load(Marshal.dump(default_value))
            end
          end

          if options[:typecast].present?
            type.from_mongo(value).map! { |v| typecast_class.from_mongo(v) }
          else
            type.from_mongo(value)
          end
        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

8 entries across 8 versions & 3 rubygems

Version Path
mongo_mapper-0.12.0 lib/mongo_mapper/plugins/keys/key.rb
lookout-mongo_mapper-0.11.3 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-0.11.2 lib/mongo_mapper/plugins/keys/key.rb
jamieorc-mongo_mapper-0.11.1.1 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-0.11.1 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-0.11.0 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-0.10.1 lib/mongo_mapper/plugins/keys/key.rb
mongo_mapper-0.10.0 lib/mongo_mapper/plugins/keys/key.rb