Created
April 25, 2013 00:39
-
-
Save thommahoney/5456712 to your computer and use it in GitHub Desktop.
Fun with Ruby modules
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module SoftDelete | |
REQUIRED_PROPERTIES = [ | |
[ :deleted_at, DataMapper::Property::DateTime ], | |
].freeze | |
def self.extended(klass) | |
REQUIRED_PROPERTIES.each do |property| | |
klass.send(:property, *property) | |
end | |
klass.send(:extend, SoftDelete::ClassMethods) | |
klass.send(:include, SoftDelete::InstanceMethods) | |
end | |
module ClassMethods | |
def active | |
self.all(deleted_at: nil) | |
end | |
end | |
module InstanceMethods | |
def active? | |
!!self.deleted_at | |
end | |
def destroy | |
self.deleted_at = Time.now; save_self(true) | |
end | |
end | |
end | |
# Instead of writing all of this... | |
class Server | |
property :deleted_at, DataMapper::Property::DateTime | |
def self.active | |
self.all(deleted_at: nil) | |
end | |
def active? | |
!!self.deleted_at | |
end | |
def destroy | |
self.deleted_at = Time.now; save_self(true) | |
end | |
end | |
# All we have to write is this | |
class Server | |
extend SoftDelete | |
end | |
# And we can reuse the code here | |
class Volume | |
extend SoftDelete | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment