Topic: DRY. How could i improve this ? (model+session)

Dear Rails Gods

Ive recently added versioning to a bunch of Models via the handy Vestal Versions gem.
In each of my models I've added a 'author' field which is the user_id of the person who is making the change to whatever model.

We grab this user id from the session where it has been stored previously.

currently, every time a versioned model is edited, we save who is doing the editing (the user) as the 'author'

Now when i first built this i thought i could simply do a before_save in the model and set the record's author there but i've since learnt i cannot access the session from the model so that killed that idea.

what i ended up doing was creating an method in the Application controller which returns the current user's ID and then i call that method from various Controller methods when creating / updating any of my versioned models..

This is all working fine, but i suspect it could be improved and id like to do so..

any thoughts?

Re: DRY. How could i improve this ? (model+session)

I'm surprise that your gem isn't handling this for you!

You could create a super class model, and inherit all your authored_models from that base model, put the code in the super class that updates the author attribute.

class AuthoredModel < ActiveRecord::Base
   def attributes(atts,auth)
      super(atts)
      update_attribute('author', auth)
   end
end

class AModel < AuthoredModel
end

Then in your controller

def update
  @amodel = AModel.find(params[:id])
  @amodel.attributes(params[:amodel], current_user???)
end

That would clean things up a bit,  but you'd still have to modify all your create/update actions.  Not great but probably a little less coding in the long run, a touch DRYer?  If that works for you,  you'd have to do the same of the new method of the model.

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: DRY. How could i improve this ? (model+session)

Hey
Thanks for that. makes sense.
I think im too deep in this app and unfortunately dont have the time to refactor all those models as you suggest.. which kinda sucks.

Just out of curiosity, What is the logic / arguement behind not allowing access to the Session through the Model?
thx

Re: DRY. How could i improve this ? (model+session)

That's a loaded question.  It goes to the heart of the whole MVC design pattern.  If you want to dig deep into the history,  read the Smalltalk-80 book by Adele Goldberg (sic), if it's still in print?  Xerox Parc SmallTalk-80 was the first real implementation of MVC,  and it's explained very well in that book.

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.