I have an application in which attr_accessor is being used to keep temporary data for a model which will be passed to a rake task. Seeing there is not a database field for these attributes and they are not being calculated from database data, will the attr_accessor data persist and be available to the rake task? What happens if I need to restart the server - does the data get lost then if it's not saved to database? Or to pull this off, do I need to either save to a temp file or a database field?
This sounds like a strange pattern (having a rake task access model attributes).
Perhaps you intend to have an application config or the like? If so, there are few plugins that handles such cases.
Can you give an example for clarity?
Of course it'll be lost, where do you think data goes when it dies? To a data h(e)aven from where it can always return?
I'd like to know what you need the data for, but the ultimate answer is probably that the data belongs into the db, unless it's large binary data such as images, where you should save it in the filesystem.
I assume you are asking whether data that is stored in attributes of ActiveRecord objects stemming from Web requests will be available when accessing them via a Rake task?
No. They won't. That data won't even be available to the next web request. That data won't even be there if you load the same record twice.
class Thing < ActiveRecord::Base
attr_accessor data
end
#try this in script/console
thing = Thing.find(:first)
thing.data = "Something"
thing = Thing.find(:first)
puts thing.data
-> nil
It depends on how you are passing your data to the rake task and why. If your trying to do the work out-of-band with the request, meaning not making the user wait until its complete I recommend taking a look at Ryan's excellent screencast here http://railscasts.com/episodes/128-starling-and-workling to learn about job queues.
If its some other exotic reason you must use rake like this you could pass the data as command line parameters. This depends on how much data, and its complexity, you need to pass as it might get out of hand quickly.
Using Daniel's example from above:
thing = Thing.find(:first) thing.data = "Something"
rake myraketask thing_id=#{thing.id} data=#{thing.data}