Hello.
LoginSystem is cool, it populates the @session instance variable of
controllers with many useful info.
The fact is : it would be cool to let models know about the session,
too.
For instance, after_update and after_create callbacks could store who
did what on *what.
Aim : having ActiveRecord::Base::session defined, returning the @session
of the controller which manipulates the model.
Here’s a way to do that. I was wondering whether it was good ruby and
good rails because I’m a real newbie. I don’t know either if the class
member I added to ActiveRecord::Base doesn’t break when several users
use the application, leading to multiple sessions.
First, let controllers give @session to models :
(In controllers/application.rb)
class ApplicationController < ActionController::Base
include LoginSystem
before_filter :export_session_to_models
def export_session_to_models
ActiveRecord::Base.set_session { @session }
end
end
Now, let models know the set_session method, and let’s define
ActiveRecord::Base::session:
(In controllers/application.rb)
This unless is required for proper behavior in FastCGI context
unless defined? ActiveRecord::Base::session
class ActiveRecord::Base
@@session = nil
class << self
def set_session(&action)
@@session = action
end
def session
@@session.call()
end
end
def session
self.class.session
end
end
end
Is this code OK ?
Now that this framework is set, I can store who did what on what on any
database update :
(In controllers/application.rb)
class ActiveRecord::Base
after_update :update_history
after_create :create_history
before_destroy :destroy_history
def update_history
history (‘update’)
end
def create_history
history (‘create’)
end
def destroy_history
history (‘destroy’)
end
def history(action)
unless kind_of?(History)
history = History.new(:action => action)
history.ref = self
history.save
end
end
end
With, roughly, a History model like :
:user_id # who performed the action
:action # the action
:date # when
:ref_table # the table of the altered model
:ref_id # the id of the altered model
(In models/history.rb)
class History < ActiveRecord::Base
def ref=(object)
write_attribute(‘ref_table’, object.class.table_name)
write_attribute(‘ref_id’, object.id)
end
before_create :fix_history
before_update :fix_history
def fix_history
write_attribute(‘user_id’, session[:user].id) if user_id.nil?
write_attribute(‘date’, Time.now) if date.nil?
end
end