Sha256: 3512aa8cd624c6836b61fd2c8ad5ca87e5f3180ed512a6f97b4d5f7e461f8560

Contents?: true

Size: 1.06 KB

Versions: 8

Compression:

Stored size: 1.06 KB

Contents

require "timespan"
require "mongoid/fields"

# Mongoid serialization support for Timespan type.
module Mongoid
  module Fields
    class Timespan
      include Mongoid::Fields::Serializable
    
      def self.instantiate(name, options = {})
        super
      end

      # Deserialize a Timespan given the hash stored by Mongodb
      #
      # @param [Hash] Timespan as hash
      # @return [Timespan] deserialized Timespan
      def deserialize(timespan_hash)
        return if !timespan_hash
        ::Timespan.new(:from => timespan_hash[:from], :to => timespan_hash[:to])
      end

      # Serialize a Timespan or a Hash (with Timespan units) or a Duration in some form to
      # a BSON serializable type.
      #
      # @param [Timespan, Hash, Integer, String] value
      # @return [Hash] Timespan in seconds
      def serialize(value)
        return if value.blank?
        timespan = ::Timespan.new(value)
        {:from => timespan.start_time, :to => timespan.end_time, :duration => timespan.duration.total}
      end
    end
  end
end

TimeSpan = Mongoid::Fields::Timespan

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
timespan-0.2.8 lib/timespan/mongoid.rb
timespan-0.2.7 lib/timespan/mongoid.rb
timespan-0.2.6 lib/timespan/mongoid.rb
timespan-0.2.5 lib/timespan/mongoid.rb
timespan-0.2.4 lib/timespan/mongoid.rb
timespan-0.2.3 lib/timespan/mongoid.rb
timespan-0.2.2 lib/timespan/mongoid.rb
timespan-0.2.1 lib/timespan/mongoid.rb