Module: Versioned::ClassMethods

Defined in:
lib/versioned.rb

Instance Method Summary collapse

Instance Method Details

#locking!(options = {}) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/versioned.rb', line 52

def locking!(options = {})
  include(LockingInstanceMethods)
  class_inheritable_accessor :version_lock_key
  self.version_lock_key = options[:key] || :lock_version
  key self.version_lock_key, Integer

  if self.respond_to?(:version_use_key)
    self.version_use_key = self.version_lock_key
    (self.version_except_columns ||= []) << self.version_lock_key.to_s #don't version the lock key 
  end
end

#versioned(options = {}) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/versioned.rb', line 64

def versioned(options = {})
  class_inheritable_accessor :version_only_columns
  self.version_only_columns = Array(options[:only]).map(&:to_s).uniq if options[:only]
  class_inheritable_accessor :version_except_columns
  self.version_except_columns = Array(options[:except]).map(&:to_s).uniq if options[:except]

  class_inheritable_accessor :version_use_key
  self.version_use_key = options[:use_key]

  many :versions, :as => :versioned, :order => 'number ASC', :dependent => :delete_all do
    def between(from, to)
      from_number, to_number = number_at(from), number_at(to)
      return [] if from_number.nil? || to_number.nil?
      condition = (from_number == to_number) ? to_number : Range.new(*[from_number, to_number].sort)
      if condition.is_a?(Range)
        conditions = {'$gte' => condition.first, '$lte' => condition.last}
      else
        conditions = condition
      end
      find(:all, 
        :number => conditions,
        :order => "number #{(from_number > to_number) ? 'DESC' : 'ASC'}"
      )
    end

    def at(value)
      case value
        when Version then value
        when Numeric then find_by_number(value.floor)
        when Symbol then respond_to?(value) ? send(value) : nil
        when Date, Time then last(:created_at => {'$lte' => value.to_time})
      end
    end

    def number_at(value)
      case value
        when Version then value.number
        when Numeric then value.floor
        when Symbol, Date, Time then at(value).try(:number)
      end
    end
  end

  after_create :create_initial_version
  after_update :create_initial_version, :if => :needs_initial_version?
  after_update :create_version, :if => :needs_version?

  include InstanceMethods
  alias_method_chain :reload, :versions
end