Module: IsParanoid::InstanceMethods

Defined in:
lib/is_paranoid.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/is_paranoid.rb', line 144

def method_missing name, *args
  # if we're trying for a _____with_destroyed method
  # and we can respond to the _____ method
  # and we have an association by the name of _____
  if name.to_s =~ /^(.*)(_with_destroyed)$/ and
      self.respond_to?($1) and
      (assoc = self.class.reflect_on_all_associations.detect{|a| a.name.to_s == $1})

    parent_klass = Object.module_eval("::#{assoc.class_name}", __FILE__, __LINE__)

    self.class.send(
      :include,
      Module.new{                                 # Example:
        define_method name do |*args|             # def android_with_destroyed
          parent_klass.first_with_destroyed(      #   Android.first_with_destroyed(
            :conditions => {                      #     :conditions => {
              parent_klass.primary_key =>         #       :id =>
                self.send(assoc.primary_key_name) #         self.send(:android_id)
            }                                     #     }
          )                                       #   )
        end                                       # end
      }
    )
    self.send(name, *args)
  else
    super(name, *args)
  end
end

Instance Method Details

#destroyObject

Override the default destroy to allow us to flag deleted_at. This preserves the before_destroy and after_destroy callbacks. Because this is also called internally by Model.destroy_all and the Model.destroy(id), we don’t need to specify those methods separately.



186
187
188
189
190
191
# File 'lib/is_paranoid.rb', line 186

def destroy
  return false if callback(:before_destroy) == false
  result = destroy_without_callbacks
  callback(:after_destroy)
  result
end

#destroy_without_callbacksObject

Mark the model deleted_at as now.



174
175
176
177
178
179
# File 'lib/is_paranoid.rb', line 174

def destroy_without_callbacks
  self.class.update_all(
    "#{destroyed_field} = #{self.class.connection.quote(( field_destroyed.respond_to?(:call) ? field_destroyed.call : field_destroyed))}",
    "id = #{self.id}"
  )
end

#restore(options = {}) ⇒ Object

Set deleted_at flag on a model to field_not_destroyed, effectively undoing the soft-deletion.



195
196
197
# File 'lib/is_paranoid.rb', line 195

def restore(options = {})
  self.class.restore(id, options)
end