How does the :save hook relate to the :update hook in DataMapper? - ruby

If I define the following model...
class Foo
include DataMapper::Resource
property :name, String, :key => true
before :save, do
puts 'save'
end
before :update, do
puts 'update'
end
end
Why does the 2nd save also trigger the 'update' hook?
ruby :001 > f = Foo.new
=> #<Foo #name=nil>
ruby :002 > f.name = 'Bob'
=> "Bob"
ruby :003 > f.save
save
=> true
ruby :004 > f.name = 'Joe'
=> "Joe"
ruby :005 > f.save
save
update
=> true
Of course I could dive into the source and answer the question of what code drives this behavior. More importantly, I want to understand the right way to use each of these hooks in practice.

require 'rubygems'
require 'data_mapper'
class Foo
include DataMapper::Resource
property :name, String, :key => true
before :create, do
puts 'Create: Only happens when saving a new object.'
end
before :update, do
puts 'Update: Only happens when saving an existing object.'
end
before :save, do
puts 'Save: Happens when either creating or updating an object.'
end
before :destroy, do
puts 'Destroy: Only happens when destroying an existing object.'
end
end
DataMapper.setup :default, 'sqlite::memory:'
DataMapper.finalize
DataMapper.auto_migrate!
puts "New Foo:"
f = Foo.new :name => "Fighter"
f.save
puts "\nUpdate Foo:"
f.name = "Bar"
f.save
puts "\nUpdate Foo again:"
f.update :name => "Baz"
puts "\nDestroy Foo:"
f.destroy
Which returns:
New Foo:
Save: Happens when either creating or updating an object.
Create: Only happens when saving a new object.
Update Foo:
Save: Happens when either creating or updating an object.
Update: Only happens when saving an existing object.
Update Foo again:
Save: Happens when either creating or updating an object.
Update: Only happens when saving an existing object.
Destroy Foo:
Destroy: Only happens when destroying an existing object.
So as you can see you'd want to use :save hooks whenever something should happen after either a create or an update, and :create and/or :update when you want a finer level of control.

Related

Accessing command line arguments from outside of Thor class

Pretty new to Ruby and OO. Studying the text books, and all the articles that google found on Thor.
I have Thor working to capture multiple command line arguments and options. I'd like to do the rest of my programming from outside the Cli < Thor class though, and am having trouble accessing the command line arguments from outside the Cli class.
Questions:
Q1. Can the Cli < Thor class be treated like any other ruby class, or does inheriting from Thor, or the "Cli.start" command, cripple certain functionality of the Cli class versus not using Thor? Asking because I may simply not know how to access an instance variable from outside a class that doesn't use the initialize method. Thor will not let me use the initialize method to bring in the command line variables, probably because initialize is a reserved method name in ruby.
Q2. How can I access the command line argument variables a and b from outside the Thor class?
Here's my code
#!/usr/bin/env ruby
require 'thor'
class Cli < Thor
attr_reader :a, :b
method_option :add, :type => :string, :desc => 'add servers'
method_option :prod, :type => :string, :desc => 'production stack'
desc "tier <stack folder name> <app | web>", "creates an app or web server tier for the stack"
def tier(a,b)
#a = a
#b = b
puts a
puts b
end
end
Cli.start
arguments = Cli.new
puts "the first argument is #{arguments.a}"
Here's the result. Close (maybe). No errors, but arguments.a is nil.
$ ./create.rb tier a b
a
b
the first argument is
--
puts arguments.tier.a
threw the error:
./create.rb:11:in `tier': wrong number of arguments (0 for 2) (ArgumentError)
from ./create.rb:23:in `<main>'
The following works without Thor and using an initialize method and attr_reader, straight out of the text books. Can't figure out how to access the variables from a non-initialize method though.
#!/usr/bin/env ruby
class Cli
attr_reader :a, :b
def initialize(a,b)
#a = a
#b = b
end
end
arguments = Cli.new("a","b")
puts arguments.a
outupt:
$ ./create_wo_thor.rb
a
Instantiating your Cli class doesn't make much sense; that's not how Thor is designed.
You have a few options to access internal data from outside the class. If there are only a few variables that you want access to, storing them as class variables and making them available through getters (and setters, if you need them) would work:
require 'thor'
class Cli < Thor
method_option :add, :type => :string, :desc => 'add servers'
method_option :prod, :type => :string, :desc => 'production stack'
desc "tier <stack folder name> <app | web>", "creates an app or web server tier for the stack"
def tier(a,b)
##a = a
##b = b
puts a
puts b
end
def self.get_a
##a
end
def self.get_b
##b
end
end
Cli.start
puts "the first argument is #{Cli.get_a}"
This works as you hope:
$ ./thor.rb tier a b
a
b
the first argument is a
I prefer the following, using a global Hash:
require 'thor'
$args = {}
class Cli < Thor
method_option :add, :type => :string, :desc => 'add servers'
method_option :prod, :type => :string, :desc => 'production stack'
desc "tier <stack folder name> <app | web>", "creates an app or web server tier for the stack"
def tier(a,b)
$args[:a] = a
$args[:b] = b
puts a
puts b
end
end
Cli.start
puts "the first argument is #{$args[:a]}"
Last, I'd be remiss not to point out that all the command line arguments are available in the global ARGV, anyway:
require 'thor'
class Cli < Thor
method_option :add, :type => :string, :desc => 'add servers'
method_option :prod, :type => :string, :desc => 'production stack'
desc "tier <stack folder name> <app | web>", "creates an app or web server tier for the stack"
def tier(a,b)
puts a
puts b
end
end
Cli.start
puts "The first argugment is #{ARGV[1]}"
What would be best depends on how you intend to use it. If you just want raw access to the command line arguments, ARGV is the way to go. If you want to access certain pieces after Thor has done some processing for you, one of the first two might be more helpful.
Here's my code with all three options included for accessing the command line arguments from outside the Cli < Thor class. Compliments to Darshan.
#!/usr/bin/env ruby
require 'thor'
$args = {}
class Cli < Thor
attr_reader :a, :b
method_option :add, :type => :string, :desc => 'add servers'
method_option :prod, :type => :string, :desc => 'production stack'
desc "tier <stack folder name> <app | web>", "creates an app or web server tier for the stack"
def tier(a,b)
# store a and b in a global hash
$args[:a] = a
$args[:b] = b
# store a and b in class variables
##a = a
##b = b
end
# getter methods, for access of the class variables from outside the class
def self.get_a
##a
end
def self.get_b
##b
end
end
Cli.start
# three ways now to access the command line arguments from outside the Cli < Thor class
puts "the first argument, from $args[:a], is #{$args[:a]}"
puts "the second argument, from Cli.get_b, is #{Cli.get_b}"
puts "the first argument, from ARGV[1], is #{ARGV[1]}"
Results:
$ ./create.rb tier a b
the first argument, from $args[:a], is a
the second argument, from Cli.get_b, is b
the first argument, from ARGV[1], is a

Ruby Motion: Removing a Ruby Class Completely from Object Space

I'm running into a brick wall testing class redefinitions and just don't know how to approach it. Here's the scenario I'm testing (this is not Core Data):
Application is run with a model in version 1
Eager programmer modifies model by adding/removing/redefining columns
Application is run with the model in version 2
Where I'm running into problems is in simulating the actual removal of the application from memory and rebuilding of it from scratch. This is important because a number of model-specific things are set up when the MotionModel::Model module is included, and that only happens once: When the module is included in the class. Here is what I felt might work:
it "column removal" do
class Removeable
include MotionModel::Model
columns :name => :string, :desc => :string
end
#foo = Removeable.create(:name=> 'Bob', :desc => 'who cares anyway?')
Removeable.serialize_to_file('test.dat')
#foo.should.respond_to :desc
Object.send(:remove_const, :Removeable) # Should remove all traces of Removeable
class Removeable
include MotionModel::model # Should include this again instead
columns :name => :string, # of just reopening the old Removeable
:address => :string # class
end
Removeable.deserialize_from_file # Deserialize old data into new model
Removeable.length.should == 1
#bar = Removeable.first
#bar.should.respond_to :name
#bar.should.respond_to :address
#bar.should.not.respond_to :desc
#bar.name.should == 'Bob'
#bar.address.should == nil
end
end
Unfortunately, Object.send(:remove_const, :Removeable) does not do what I'd hoped it would, and Ruby just thinks it can reopen Removeable and not run the self.included() method of the MotionModel::Model module.
Any ideas on how to emulate creation of this class from scratch in the context of a spec example?
I'd try working with anonymous classes (you'd have to tell MotionModel the table name).
Fictional example:
model_before_update = Class.new do
# This tells MotionModel the name of the class (don't know if that actually exists)
table_name "SomeTable"
include MotionModel::Model
columns :name => :string, :desc => :string
end
You do not remove the class at all, you just define another (anonymous) class with the same table name.
model_after_update = Class.new do
table_name "SomeTable"
include MotionModel::model
columns :name => :string,
:address => :string
end
Thinking of it, if there is a table_name setter like above, you don't even need to use anonymous classes, in case that does not work with RubyMotion.

How can I reload the table schema in sequel?

Given I have the following migration:
Sequel.migration do
up do
alter_table :users do
add_column :is_admin, :default => false
end
# Sequel runs a DESCRIBE table statement, when the model is loaded.
# At this point, it does not know that users have a is_admin flag.
# So it fails.
#user = User.find(:email => "admin#fancy-startup.example")
#user.is_admin = true
#user.save!
end
end
Then sequel does not automatically reload the table structure (see comment inline).
I am using this ugly hack to work around it:
# deep magic begins here. If you remove a single line, it will
# break the migration.
User.db.schema("users", :reload => true)
User.instance_variable_set(:#db_schema, nil)
User.columns
User.new.respond_to?(:is_admin=)
sleep 1
Is there a better way?
Much simpler than your hack is this hack: (re)set the dataset to the table name:
User.set_dataset :users
Seen in action:
require 'sequel'
DB = Sequel.sqlite
DB.create_table :users do
primary_key :id
String :name
end
class User < Sequel::Model; end
User << { name:"Bob" }
DB.alter_table :users do
add_column :is_admin, :boolean, default:false
end
p User.first #=> #<User #values={:id=>1, :name=>"Bob", :is_admin=>false}>
p User.setter_methods #=> ["name="]
User.set_dataset :users # Make the magic happen
p User.setter_methods #=> ["name=", "is_admin="]
#user = User.first
#user.is_admin = true
#user.save
p User.first #=> #<User #values={:id=>1, :name=>"Bob", :is_admin=>true}>
Note that there is no Sequel::Model#save! method; I changed it to save so that it would work.

Ruby structure for extendable handler/plugin architechture

I'm writing something that is a bit like Facebook's shared link preview.
I would like to make it easily extendable for new sites by just dropping in a new file for each new site I want to write a custom parser for. I have the basic idea of the design pattern figured out but don't have enough experience with modules to nail the details. I'm sure there are plenty of examples of something like this in other projects.
The result should be something like this:
> require 'link'
=> true
> Link.new('http://youtube.com/foo').preview
=> {:title => 'Xxx', :description => 'Yyy', :embed => '<zzz/>' }
> Link.new('http://stackoverflow.com/bar').preview
=> {:title => 'Xyz', :description => 'Zyx' }
And the code would be something like this:
#parsers/youtube.rb
module YoutubeParser
url_match /(youtube\.com)|(youtu.be)\//
def preview
get_stuff_using youtube_api
end
end
#parsers/stackoverflow.rb
module SOFParser
url_match /stachoverflow.com\//
def preview
get_stuff
end
end
#link.rb
class Link
def initialize(url)
extend self with the module that has matching regexp
end
end
# url_processor.rb
class UrlProcessor
# registers url handler for given pattern
def self.register_url pattern, &block
#patterns ||= {}
#patterns[pattern] = block
end
def self.process_url url
_, handler = #patterns.find{|p, _| url =~ p}
if handler
handler.call(url)
else
{}
end
end
end
# plugins/so_plugin.rb
class SOPlugin
UrlProcessor.register_url /stackoverflow\.com/ do |url|
{:title => 'foo', :description => 'bar'}
end
end
# plugins/youtube_plugin.rb
class YoutubePlugin
UrlProcessor.register_url /youtube\.com/ do |url|
{:title => 'baz', :description => 'boo'}
end
end
p UrlProcessor.process_url 'http://www.stackoverflow.com/1234'
#=>{:title=>"foo", :description=>"bar"}
p UrlProcessor.process_url 'http://www.youtube.com/1234'
#=>{:title=>"baz", :description=>"boo"}
p UrlProcessor.process_url 'http://www.foobar.com/1234'
#=>{}
You just need to require every .rb from plugins directory.
If you're willing to take this approach you should probably scan the filed for the mathing string and then include the right one.
In the same situation I attempted a different approach. I'm extending the module with new methods, ##registering them so that I won't register two identically named methods. So far it works good, though the project I started is nowhere near leaving the specific domain of one tangled mess of a particular web-site.
This is the main file.
module Onigiri
extend self
##registry ||= {}
class OnigiriHandlerTaken < StandardError
def description
"There was an attempt to override registered handler. This usually indicates a bug in Onigiri."
end
end
def clean(data, *params)
dupe = Onigiri::Document.parse data
params.flatten.each do |method|
dupe = dupe.send(method) if ##registry[method]
end
dupe.to_html
end
class Document < Nokogiri::HTML::DocumentFragment
end
private
def register_handler(name)
unless ##registry[name]
##registry[name] = true
else
raise OnigiriHandlerTaken
end
end
end
And here's the extending file.
# encoding: utf-8
module Onigiri
register_handler :fix_backslash
class Document
def fix_backslash
dupe = dup
attrset = ['src', 'longdesc', 'href', 'action']
dupe.css("[#{attrset.join('], [')}]").each do |target|
attrset.each do |attr|
target[attr] = target[attr].gsub("\\", "/") if target[attr]
end
end
dupe
end
end
end
Another way I see is to use a set of different (but behaviorally indistinguishable) classes with a simple decision making mechanism to call a right one. A simple hash that holds class names and corresponding url_matcher would probably suffice.
Hope this helps.

Rails audit system with both ActiveResource and ActiveRecord

I have a huge project with both of ActiveRecord and ActiveResource models. I need to implement logging of user activity with these models and also to log changes of model attributes (save object state or somthing like that). Changes can made by users or cron rake tasks.
I also must have possibility to search any data by date , any field ..etc
Will be nice also to generate readable messages with last activity , for example
User Bob change his password to * and email to ** at 2011-08-12 08:12
Staff Jeff added new partner: Company name at 2011-08-12 08:13
Admin Jack deleted product : Product name at 2011-09-12 11:11
Client Sam ordered new service : Service name at 2011-09-12 11:12
Does anybody implement such logging? Ideas? Advices?
should I use gems or can I do all the logic with observers not changing models?
I liked gem https://github.com/airblade/paper_trail can anybody say how can I make it work with activeresource ?
You are looking for
https://github.com/collectiveidea/acts_as_audited
Few open source projects use that plugin I think Red Mine as well as The Foreman.
Edit: Unfortunately it can do only ActiveRecord, not ActiveResource.
Fivell, I just saw this question and don't have time to work up alterations this evening before the bounty expires, so I'll give you my auditing code that works with ActiveRecord and should work with ActiveResource, perhaps with a few tweaks (I don't use ARes often enough to know offhand). I know the callbacks we use are there, but I'm not sure if ARes has ActiveRecord's dirty attribute changes tracking.
This code logs each CREATE/UPDATE/DELETE on all models (excepting CREATEs on the audit log model and any other exceptions you specify) with the changes stored as JSON. A cleaned backtrace is also stored so you can determine what code made the change (this captures any point in your MVC as well as rake tasks and console usage).
This code works for console usage, rake tasks, and http requests, although generally only the last one logs the current user. (If I recall correctly, the ActiveRecord observer that this replaced did not work in rake tasks or the console.) Oh, this code comes from a Rails 2.3 app - I have a couple Rails 3 apps, but I haven't needed this kind of auditing for them yet.
I don't have code that builds a nice display of this information (we only dig into the data when we need to look into an issue), but since the changes are stored as JSON it should be fairly straightforward.
First, we store the current user in User.current so it is accessible everywhere, so in app/models/user.rb:
Class User < ActiveRecord::Base
cattr_accessor :current
...
end
The current user is set in the application controller for each request like so (and does not cause concurrency issues):
def current_user
User.current = session[:user_id] ? User.find_by_id(session[:user_id]) : nil
end
You could set User.current in your rake tasks if it made sense to.
Next, we define the model to store the audit info app/models/audit_log_entry.rb - you'll want to customize IgnoreClassesRegEx to fit any models you don't want audited:
# == Schema Information
#
# Table name: audit_log_entries
#
# id :integer not null, primary key
# class_name :string(255)
# entity_id :integer
# user_id :integer
# action :string(255)
# data :text
# call_chain :text
# created_at :datetime
# updated_at :datetime
#
class AuditLogEntry < ActiveRecord::Base
IgnoreClassesRegEx = /^ActiveRecord::Acts::Versioned|ActiveRecord.*::Session|Session|Sequence|SchemaMigration|CronRun|CronRunMessage|FontMetric$/
belongs_to :user
def entity (reload = false)
#entity = nil if reload
begin
#entity ||= Kernel.const_get(class_name).find_by_id(entity_id)
rescue
nil
end
end
def call_chain
return if call_chain_before_type_cast.blank?
if call_chain_before_type_cast.instance_of?(Array)
call_chain_before_type_cast
else
JSON.parse(call_chain_before_type_cast)
end
end
def data
return if data_before_type_cast.blank?
if data_before_type_cast.instance_of?(Hash)
data_before_type_cast
else
JSON.parse(data_before_type_cast)
end
end
def self.debug_entity(class_name, entity_id)
require 'fastercsv'
FasterCSV.generate do |csv|
csv << %w[class_name entity_id date action first_name last_name data]
find_all_by_class_name_and_entity_id(class_name, entity_id,
:order => 'created_at').each do |a|
csv << [a.class_name, a.entity_id, a.created_at, a.action,
(a.user && a.user.first_name), (a.user && a.user.last_name), a.data]
end
end
end
end
Next we add some methods to ActiveRecord::Base to make the audits work. You'll want to look at the audit_log_clean_backtrace method and modify for your needs. (FWIW, we put additions to existing classes in lib/extensions/*.rb which are loaded in an initializer.) In lib/extensions/active_record.rb:
class ActiveRecord::Base
cattr_accessor :audit_log_backtrace_cleaner
after_create :audit_log_on_create
before_update :save_audit_log_update_diff
after_update :audit_log_on_update
after_destroy :audit_log_on_destroy
def audit_log_on_create
return if self.class.name =~ /AuditLogEntry/
return if self.class.name =~ AuditLogEntry::IgnoreClassesRegEx
audit_log_create 'CREATE', self, caller
end
def save_audit_log_update_diff
#audit_log_update_diff = changes.reject{ |k,v| 'updated_at' == k }
end
def audit_log_on_update
return if self.class.name =~ AuditLogEntry::IgnoreClassesRegEx
return if #audit_log_update_diff.empty?
audit_log_create 'UPDATE', #audit_log_update_diff, caller
end
def audit_log_on_destroy
return if self.class.name =~ AuditLogEntry::IgnoreClassesRegEx
audit_log_create 'DESTROY', self, caller
end
def audit_log_create (action, data, call_chain)
AuditLogEntry.create :user => User.current,
:action => action,
:class_name => self.class.name,
:entity_id => id,
:data => data.to_json,
:call_chain => audit_log_clean_backtrace(call_chain).to_json
end
def audit_log_clean_backtrace (backtrace)
if !ActiveRecord::Base.audit_log_backtrace_cleaner
ActiveRecord::Base.audit_log_backtrace_cleaner = ActiveSupport::BacktraceCleaner.new
ActiveRecord::Base.audit_log_backtrace_cleaner.add_silencer { |line| line =~ /\/lib\/rake\.rb/ }
ActiveRecord::Base.audit_log_backtrace_cleaner.add_silencer { |line| line =~ /\/bin\/rake/ }
ActiveRecord::Base.audit_log_backtrace_cleaner.add_silencer { |line| line =~ /\/lib\/(action_controller|active_(support|record)|hoptoad_notifier|phusion_passenger|rack|ruby|sass)\// }
ActiveRecord::Base.audit_log_backtrace_cleaner.add_filter { |line| line.gsub(RAILS_ROOT, '') }
end
ActiveRecord::Base.audit_log_backtrace_cleaner.clean backtrace
end
end
Finally, here are the tests we have on this - you'll need to modify the actual test actions of course. test/integration/audit_log_test.rb
require File.dirname(__FILE__) + '/../test_helper'
class AuditLogTest < ActionController::IntegrationTest
def setup
end
def test_audit_log
u = users(:manager)
log_in u
a = Alert.first :order => 'id DESC'
visit 'alerts/new'
fill_in 'alert_note'
click_button 'Send Alert'
a = Alert.first :order => 'id DESC', :conditions => ['id > ?', a ? a.id : 0]
ale = AuditLogEntry.first :conditions => {:class_name => 'Alert', :entity_id => a.id }
assert_equal 'Alert', ale.class_name
assert_equal 'CREATE', ale.action
end
private
def log_in (user, password = 'test', initial_url = home_path)
visit initial_url
assert_contain 'I forgot my password'
fill_in 'email', :with => user.email
fill_in 'password', :with => password
click_button 'Log In'
end
def log_out
visit logout_path
assert_contain 'I forgot my password'
end
end
And test/unit/audit_log_entry_test.rb:
# == Schema Information
#
# Table name: audit_log_entries
#
# id :integer not null, primary key
# class_name :string(255)
# action :string(255)
# data :text
# user_id :integer
# created_at :datetime
# updated_at :datetime
# entity_id :integer
# call_chain :text
#
require File.dirname(__FILE__) + '/../test_helper'
class AuditLogEntryTest < ActiveSupport::TestCase
test 'should handle create update and delete' do
record = Alert.new :note => 'Test Alert'
assert_difference 'Alert.count' do
assert_difference 'AuditLogEntry.count' do
record.save
ale = AuditLogEntry.first :order => 'created_at DESC'
assert ale
assert_equal 'CREATE', ale.action, 'AuditLogEntry.action should be CREATE'
assert_equal record.class.name, ale.class_name, 'AuditLogEntry.class_name should match record.class.name'
assert_equal record.id, ale.entity_id, 'AuditLogEntry.entity_id should match record.id'
end
end
assert_difference 'AuditLogEntry.count' do
record.update_attribute 'note', 'Test Update'
ale = AuditLogEntry.first :order => 'created_at DESC'
expected_data = {'note' => ['Test Alert', 'Test Update']}
assert ale
assert_equal 'UPDATE', ale.action, 'AuditLogEntry.action should be UPDATE'
assert_equal expected_data, ale.data
assert_equal record.class.name, ale.class_name, 'AuditLogEntry.class_name should match record.class.name'
assert_equal record.id, ale.entity_id, 'AuditLogEntry.entity_id should match record.id'
end
assert_difference 'AuditLogEntry.count' do
record.destroy
ale = AuditLogEntry.first :order => 'created_at DESC'
assert ale
assert_equal 'DESTROY', ale.action, 'AuditLogEntry.action should be CREATE'
assert_equal record.class.name, ale.class_name, 'AuditLogEntry.class_name should match record.class.name'
assert_equal record.id, ale.entity_id, 'AuditLogEntry.entity_id should match record.id'
assert_nil Alert.find_by_id(record.id), 'Alert should be deleted'
end
end
test 'should not log AuditLogEntry create entry and block on update and delete' do
record = Alert.new :note => 'Test Alert'
assert_difference 'Alert.count' do
assert_difference 'AuditLogEntry.count' do
record.save
end
end
ale = AuditLogEntry.first :order => 'created_at DESC'
assert_equal 'CREATE', ale.action, 'AuditLogEntry.action should be CREATE'
assert_equal record.class.name, ale.class_name, 'AuditLogEntry.class_name should match record.class.name'
assert_equal record.id, ale.entity_id, 'AuditLogEntry.entity_id should match record.id'
assert_nil AuditLogEntry.first(:conditions => { :class_name => 'AuditLogEntry', :entity_id => ale.id })
if ale.user_id.nil?
u = User.first
else
u = User.first :conditions => ['id != ?', ale.user_id]
end
ale.user_id = u.id
assert !ale.save
assert !ale.destroy
end
end
https://github.com/collectiveidea/acts_as_audited
and
https://github.com/airblade/paper_trail
are both great solutions for ActiveRecord only, but since much of ActiveRecord has been extracted to ActiveModel, it's likely to be reasonable to extend either to support ActiveResource as well, at least for read-only support. I looked through the Github network graphs and googled around and there doesn't appear to be any ongoing development of such a solution, nevertheless I expect it will be easier to implement on top of one of these two plugins than starting from scratch. paper_trail appears to be under more active development and has some commits for Rails 3.1, so it may be more up to date with Rails internals and easier to extend, but that's just a gut instinct—I'm not familiar with the internals of either.
The acts_as_audited gem should work well for you:
https://github.com/collectiveidea/acts_as_audited
And as far as ActiveResource is considered, it will also be a model in some other application. You can use the gem at the server side, and you don't need to audit it at the client side. All the CRUD operations using ActiveResource would finally translate to CRUD operations on the ActiveRecord (on server side).
So probably you need to look at it from a distance, and the same solution would apply in both the cases, but at different places.
for tracking user activity(CRUD ), i've created a class inherits from Logger, and now I am planing to write a litle plugin for tracking user that i can use for any ROR application built. I have already checked if there is a plugin like that but I didn’t see. I guess there are many gem like paper-trail, acts_as_audited or itslog but i prefer to use a plugin. Any suggestions?
Here is a link that might help you : http://robaldred.co.uk/2009/01/custom-log-files-for-your-ruby-on-rails-applications/comment-page-1/#comment-342
nice coding

Resources