Sha256: acfdc73b53350c4225fc84bf20c4cdb2b98534f4fea950216e3cf9a6f6e1091b

Contents?: true

Size: 1.31 KB

Versions: 16

Compression:

Stored size: 1.31 KB

Contents

module MongoModel
  module Attributes
    module Typecasting
      def []=(key, value)
        values_before_typecast[key] = value
        
        result = super(key, typecast(key, value))
        result.parent_document = instance if result.respond_to?(:parent_document=)
        result
      end
      
      # Check if key has a value that typecasts to true.
      #
      # attributes = Attributes::Store.new(:comments_count => Property.new(:comments_count, Integer))
      #
      # attributes[:comments_count] = 0
      # attributes.has?(:comments_count)
      # => false
      #
      # attributes[:comments_count] = 1
      # attributes.has?(:comments_count)
      # => true
      #
      def has?(key)
        value = self[key]
        boolean_typecast(key, value)
      end
      
      def before_type_cast(key)
        values_before_typecast[key]
      end
    
    private
      def typecast(key, value)
        unless value.nil?
          property = properties[key]
          property ? property.cast(value) : value
        end
      end
      
      def boolean_typecast(key, value)
        if property = properties[key]
          value ? property.boolean(value) : false
        else
          !!value
        end
      end
      
      def values_before_typecast
        @values_before_typecast ||= {}
      end
    end
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
mongomodel-0.2.18 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.17 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.16 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.15 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.14 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.13 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.12 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.11 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.10 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.9 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.8 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.7 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.6 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.5 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.4 lib/mongomodel/attributes/typecasting.rb
mongomodel-0.2.3 lib/mongomodel/attributes/typecasting.rb