Skip to content

Instantly share code, notes, and snippets.

@thhermansen
Created September 7, 2011 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thhermansen/1201084 to your computer and use it in GitHub Desktop.
Save thhermansen/1201084 to your computer and use it in GitHub Desktop.
ORM base class simplified
class Base
end
class Base
include Persistence
end
class Base
include Persistence
include Validations
end
class Base
include Persistence
include Dirty
include Validations
end
module Dirty
extend ActiveSupport::Concern
include ActiveModel::Dirty
def save(*)
if status = super
changes_before_save = changes
clear_dirty_states!
@previously_changed = changes_before_save
end
status
end
def write_attribute(attr_name, value)
# Logic for tracking changes, calling super
# to write attributes.
end
private
def update(*)
changes.empty? ? true : super(changes.keys)
end
end
module Persistence
def save
create_or_update
end
def destroy
# Do destroy logic
@destroyed = true
end
private
def create_or_update
new_record? create : update
end
def create
# Make call to database
@new_record = false
end
def update(attributes_to_update = all_known_attributes)
# Make call do database, update only the attributes
# we are instructed to. By default, all of them.
end
end
module Validations
extend ActiveSupport::Concern
include ActiveModel::Validations
module ClassMethods
def create!(*args)
record = new(*args)
record.save!
record
end
end
def save(options = {})
perform_validation(options) ? super : false
end
private
def perform_validation(options = {})
perform_validation = options[:validate] != false
perform_validation ? valid? : true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment