This is a little plugin, inspired by James Aylett's django_session_stashable.
It allows you to keep track of things you want to stash in the session - it's useful for doing lazy registrations.
Install like:
rails plugin install [email protected]:whilefalse/rails-3-acts-as-stashable.git
Even better:
Add this to your Gemfile:
gem 'rails-3-acts-as-stashable', :git => '[email protected]:whilefalse/rails-3-acts-as-stashable.git'
Then:
bundle install
Setup your model like so:
class MyModel < ActiveRecord::Base
acts_as_stashable
end
@thing = Thing.create(params[:thing])
@thing.stash(session)
Note that the object must be saved to the database first - we only store the id in the session as storing everything would be a bit silly.
@thing = Thing.find(1)
@thing.unstash(session) if @thing.stashed?(session)
Note the +stashed?+ method that checks if the object is stashed currently.
Thing.stashed(session)
Note that this returns an Arel relation, so you can do stuff like
Thing.stashed(session).includes(:relation)
If you're doing lazy registration stuff, this is useful. You'll have a bunch of stuff stashed in the session, and when a user signs up, you'll want to make sure they're all made to relate to the new user.
Thing.reparent_all(session, :field, value) #Updated :field to value on all stashed Things, saves them and unstashes them
Thing.reparent_all(session, :field, value, false) #Same as above but doesn't unstash the objects (not sure why you'd want this)
You can also reparent using a block - the model object will be yielded for each object being reparented. The setting of the field will be skipped, but the object will be save!'d and unstashed after your block finishes (unless unstash is false). This is identical to the first line above:
Thing.reparent_all(session) do |thing|
thing.field = value
end
cd path/to/rails-3-acts-as-stashable
rake spec
The tests use their own in memory database to run tests on a Post model.