[ Posted by James Harton
Tue, 08 Dec 2009 22:18:42 GMT ]
After yesterday releasing the initial version of Auditable I have added a few extra features, the most important of which is a Model.auditable? method so you can tell from other parts of the model whether you're dealing with a model that potentially has audit logs.
In my application I will be using a controller called audit_controller.rb which contains only the index method and will be nested below controllers for almost every model that is using Auditable. The first thing you need to do is set up your routes, my application has two controllers called remote_servers_controller and tasks_controller, both of which are auditable. We'll set up nested routes by mapping their resources, however we only want to route the index method because we don't want anyone to be able to change the audit logs. My config/routes.rb file looks like this:
ActionController::Routing::Routes.draw do |map|
map.resources :tasks do |controller|
controller.resources :audits, :only => :index
end
map.resources :remote_servers do |controller|
controller.resources :audits, :only => :index
end
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
Next we need to create an audits_controller.rb file in app/controllers to handle these requests:
class AuditsController < ApplicationController
before_filter :find_auditable_parent
def index
@audits = @parent.audits.find(:all, :order => 'audits.created_at DESC')
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @audits }
end
end
protected
def find_auditable_parent
# Use find parent to dynamically figure out
# what the parent model for this request is
if self.find_parent
# Check if that model is auditable.
if @parent.class.auditable?
true
else
false
end
end
end
end
As you can see we access the parent model's audits method to limit the scope of our find so that we only show audits about that particular model. You'll notice that there is a before_filter applied to this controller calling a method called find_parent_auditable, which is what is used to verify that the @parent variable is auditable. find_parent_auditable also calls self.find_parent which is such a common pattern with nested resources that I wound up writing something generic and including it in my ApplicationController:
def find_parent
# Dynamically figure out and what the parent
# model is for a nested resources request.
params.each do |key,val|
if key[-3..-1] == '_id'
# parameter is potentially an FK field.
potential_model = key[0..-4]
if !potential_model.empty?
# only keep processing if the name is not
# empty.
begin
model = Object.const_get potential_model.camelize
if model.ancestors.member? ActiveRecord::Base
if val.to_i > 0
@parent = model.find(val.to_i)
true
else
# no point trying to clone the model if the
# id doesn't make sense.
false
end
else
# If the Class 'PotentialModel' is not a subclass of
# ActiveRecord::Base then return false.
false
end
rescue NameError
# If there is no Class by the name of 'PotentialModel'
# then return false.
false
end
end
end
end
end
As you can see this function iterates through params looking for variables like remote_server_id, it uses that to attempt to imply the name of the model. It checks the model to see if it has ActiveRecord::Base as an ancestor, in which case it populates @parent with the correct instance of the model and returns true, telling the before_filter that it can allow the request to proceed to the controller.
Now all you need to do is create app/views/audits/index.erb to display your audit logs.
Posted in Rails, Projects | Tags auditable, log, logs, rails, ruby | no comments
[ Posted by James Harton
Tue, 08 Dec 2009 01:45:06 GMT ]
This afternoon I threw together a Rails plugin to keep audit logs of any changes made to your models. It makes use of ActiveRecord's polymorphic relationships to attach an Audit model to every model you specify.
Installing Auditable
From within your Rails application I would suggest using the plugin script to install the latest version of Auditable directly from GitHub and checking for updates regularly.
# ./script/plugin install git://github.com/jamesotron/Auditable.git
Initialized empty Git repository in /Users/jnh/tmp/test/vendor/plugins/Auditable/.git/
remote: Counting objects: 22, done.
remote: Compressing objects: 100% (19/19), done.
remote: Total 22 (delta 4), reused 0 (delta 0)
Unpacking objects: 100% (22/22), done.
From git://github.com/jamesotron/Auditable
* branch HEAD -> FETCH_HEAD
* Generating model and migration...
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/audit.rb
create test/unit/audit_test.rb
create test/fixtures/audits.yml
create db/migrate
create db/migrate/20091208005219_create_audits.rb
* Making model polymorphic...
* You probably want to run rake db:migrate now.
* Done.
Auditable will generate a model and migration called Audit, which you can safely remove if you don't want to use the default model. If you want to use the default Audit model then run
# rake db:migrate
(in /Users/jnh/tmp/test)
== CreateAudits: migrating ===================================================
-- create_table(:audits)
-> 0.0032s
== CreateAudits: migrated (0.0035s) ==========================================
to create the table in your database. You can always add any additional fields you may want using a migration.
Enabling Auditable on your models
Enabling an audit log on your model is now as simple as adding a single line to the model definition:
class WorrisomeData < ActiveRecord::Base
acts_as_auditable
end
acts_as_auditable defaults to the most paranoid setting by basically turning on all auditing by default, you can override them with options that make sense to your installation. Options available are:
:using => symbol pointing to the polymorphic model to use for storing audit logs. Defaults to :auditable. Only useful if you are defining your own Audit model.
:relation => symbol pointing to the relationship mapping for audit longs. Defaults to :audits. Useful if you want to access the audit log by a method other than Model.audits().
:when => [] an array containing symbols describing on which actions to write audit logs. Defaults to [ :accessed, :modified, :saved, :created, :deleted ].
:identity => lambda block containing any code needed to retrieve the user identifier. Defaults to lambda { "Unknown user" }. You might want to try something like lamba { ApplicationController.session[:current_user].name } if you are using restful_authentication.
:for => [] an array of symbols naming the model fields you wish to audit. Defaults to [ :all ] where :all is a special name symbolising all fields. Note you can never audit :id because it will cause an infinite loop, however Auditable will log if :id is changed.
:log_field => A symbol naming the text field in the auditor model to store the log information in. Only useful if you need something more than the default Audit model.
:identity_field => A symbol naming the string field in the auditor model to store the user's identity information in. Only useful if you need something more than the default Audit model.
Posted in Rails, Projects | Tags auditable, logging, rails, ruby | no comments
[ Posted by James Harton
Tue, 26 May 2009 04:11:21 GMT ]
So I don't think it's any secret that I am not a big fan of Redhat and it's products. Sure, they've funded some great Linux projects, but their operating system continually lags behind it's major competitors.
Installing Rails on RHEL5 is an almost entirely manual process, but sticking with my philosophy of doing as little work myself as possible, I'll use Redhat's package manager yum to install as much as we can; turns out that's not much:
~ # yum install ruby ruby-devel ruby-libs ruby-irb ruby-rdoc subversion-ruby
Okay, so at least we have a working Ruby. Next we need to get Rubygems installed:
~ # wget http://rubyforge.org/frs/download.php/35284/rubygems-1.1.1.zip
~ # unzip rubygems-1.1.1.zip
~ # cd rubygems-1.1.1
rubygems-1.1.1 # ruby setup.rb
rubygems-1.1.1 # cd ..
~ # rm -rf rubygems-1.1.1
Next, since it may be years later that you are reading this, you probably want to run gem update to update to the latest version.
Next, use Rubygems to install Rails:
~ # gem install rails
Now you're ready to start coding. Just for comparison's sake, let's look at that whole process on Debian or Ubuntu from a completely clean fresh install:
~ # apt-get install rails
'Nuff said. Thanks to Tech Trivia for the pointers.
Posted in Rails | Tags debian, howto, install, linux, rails, redhat, rhel5, ubuntu | 2 comments
[ Posted by James Harton
Fri, 22 May 2009 04:33:16 GMT ]
I've just thrown together a small widget for
Stalkr that allows you to display your contact information on your blog or website. It's really easy to use, just add the following code to your page where you want the widget to be:
<script type="text/javascript" src="http://www.stalkr.cc/widget/jamesotron"></script>
obviously replacing "jamesotron" with your Stalkr login. You can see the output on the top right of this page.
Feedback is appreciated.
Posted in Rails, Projects, Stalkr | 2 comments
[ Posted by James Harton
Mon, 18 May 2009 22:38:23 GMT ]
I've been spending a bit of time lately thinking about where to get our creative projects hosted. I hesitate to call projects like Flittr artistic, but they're definitely creative. I think of it as a toy. Currently Flittr is hosted on Marek's VM but since cheap VM's operate on low memory footprints and Marek has his own Mono projects to host I can't host any additional projects on his box, even with Passenger and Ruby Enterprise keeping the memory usage to a miminum.
Of course, given Marek's well documented love for Mono he has suggested we try using IronRuby, which I'm happy to give a go but not on the production system (and I don't have time at the moment to set up a development environment).
That's where Heroku comes in. Heroku is a cloud-based Ruby hosting service, from their site:
Heroku is a platform for instant deployment of Ruby/Rails web apps.
Heroku is a completely novel approach to deploying web applications. Forget about servers; the fundamental unit is the
app. Use the Heroku client gem to create and manage apps from the command line. Then deploy your code with Git, and
control the running app with the remote Ruby console and rake commands.
Sounds good. What's the catch? Well, for free you get 1 dyno and 5MB of storage. Which is great unless your app uses a lot of resources. Now Flittr uses relatively little CPU and RAM (well, as little as any Rails app can) but has a growing database (currently 68MB) because it stores the state of every Flittr ever sent to someone's browser for repeatability and stores basic image metadata because hitting Flickr for each image is a very costly operation. So, if you have a small Rails app then definitely look at Heroku first. What are your other options? We'll cover them in the next installment.
Posted in Rails, Projects, Meta, Flittr | no comments
[ Posted by James Harton
Sun, 17 May 2009 23:45:06 GMT ]
Somehow it's fitting that my first blog post here on Mashd should be about getting Typo to run on Heroku. I kept getting errors about conflicting gems. It seems that json-1.1.3 is bundled in vendor/gems by Typo when you run the installed. In order to fix it I had to do:
$ git rm -r vendor/gems/json-1.1.3
$ rm -rf vendor/gems/json-1.1.3
$ git commit -m "rm json gem from typo"
$ git push heroku master
Posted in Rails, Meta | Tags gems, heroku, json, mashd, rails, typo | 1 comment
[ Posted by James Harton
Tue, 19 May 2009 00:45:12 GMT ]
I have just finished deploying the alpha of Flittr, a toy that mashes up tweets with images on Flickr. I'm using Rails for rapid development and the Twitter4R and Fleakr gems. I'm keen for feedback.
Posted in Rails, Mashups, Projects, Flittr | Tags agile, api, fleakr, flickr, mashup, rails, rapid, rest, ruby, twitter, twitter4r | no comments