And here is the solution ;) Automagically implements itself into all
models except itself of course. ;)
module DataMapper
module Stamped
module Stamper
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def current_user=(user)
Thread.current["#{self.to_s.downcase}_#{self.object_id}_stamper"]
= user
end
def current_user
Thread.current["#{self.to_s.downcase}_#{self.object_id}_stamper"]
end
end
end
def self.included(model)
return if model.name == 'ActionLog'
model.after :create do _log(:create); end
model.after :update do _log(:update); end
model.before :destroy do _log(:destroy); end
model.extend ClassMethods
end
private
def _log(action)
log = {
:action => action,
:klass => self.class,
:record => self.id,
:user => User.current_user
}
::ActionLog.create(log).errors
end
module ClassMethods
def created_by
ActionLog.first({
:action => :create,
:klass => self.class,
:record => self.id
}).user
end
def updated_by
ActionLog.first({
:action => :update,
:klass => self.class,
:record => self.id
}, :order => [:time.desc]).user
end
def deleted_by
ActionLog.first({
:action => :destroy,
:klass => self.class,
:record => self.id
}, :order => [:time.desc]).user
end
end # module ClassMethods
end # module Stamped
Resource::append_inclusions Stamped
end # module DataMapper
Any ideas or additions are appreciated!
On Aug 29, 8:27 pm, fbettag <[email protected]> wrote:
> Hey guys,
>
> i've been trying to port my Logging-Class from liftweb's metamapper to
> datamapper.
>
> The idea is:
> - having a model called ActionLog
> - having hooks in a DM-model (like include MyLogClass::Logged)
> - getting every change logged (unlike only updated/created dates)
>
> The model only consists of this:
>
> class ActionLog
> include DataMapper::Resource
>
> property :id, Serial
> property :action, String, :length => 20, :nullable =>
> false
> property :klass, String, :length => 50, :nullable =>
> false
> property :record, String, :length => 30, :nullable =>
> false
> property :time, DateTime, :default => Proc.new { |r,p|
> Time.now }, :writer => :private
>
> belongs_to :user
>
> end
>
> module ActionLogging
>
> module Stamped
>
> after :create do _log(:create); end
> after :update do _log(:update); end
> after :create do _log(:delete); end
>
> def _log(action)
> log = {
> :action => action,
> :klass => self.class,
> :record => self.id,
> :user => User.current
> }
> ActionLog.create(log)
>
> end
> end
>
> end
>
> In Models which will get stamped i do:
> include ActionLogging::Stamped
>
> Is my approach the right way? because it seems i am doing something
> wrong. ;)
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"DataMapper" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/datamapper?hl=en
-~----------~----~----~----~------~----~------~--~---