Skip to content

Instantly share code, notes, and snippets.

@xeviknal
Last active August 29, 2015 14:24
Show Gist options
  • Save xeviknal/36aac3f3a7cc0d0a3661 to your computer and use it in GitHub Desktop.
Save xeviknal/36aac3f3a7cc0d0a3661 to your computer and use it in GitHub Desktop.
Smart Status - keep updated status attribute depending on datetime model's attribute

Smart Status usage:

event = Event.create
event.status # nil

event.scheduled_at = Time.now
event.save! 
event.status # scheduled

event.started_at = Time.now
event.save! 
event.status # started

For those events created before adding smart status, there is 'force_update_status' which is setting up the first value

event = Event.find 1
event.finished_at # '2015-07-08 18:21:23'
event.status # nil, created before smart status
event.force_update_status
event.save # true
event.satus # finished
class CreateEvent < ActiveRecord::Migration
def change
create_table :events do |t|
t.string :status
t.datetime :scheduled_at
t.datetime :started_at
t.datetime :finished_at
t.datetime :canceled_at
t.timestamps
end
end
end
class Event < ActiveRecord::Base
include SmartStatus
attr_accessible :scheduled_at, :started_at, :finished_at, :canceled_at
status :scheduled, :started, :finished, :canceled
end
require 'active_support/concern'
module SmartStatus
extend ActiveSupport::Concern
included do
before_save :update_status
end
def force_update_status
self.class.monitored_status.each do |status|
if self.send("#{status}_at").present?
self.send("status=", status)
end
end
end
def update_status
self.class.monitored_status.each do |status|
if self.send("#{status}_at_changed?")
self.send("status=", status)
end
end
end
module ClassMethods
def monitored_status
@monitored_status ||= []
end
def status(*args)
args.each do |arg|
monitored_status << arg
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment