On 12.06.2006, at 21:32, P.Mark Anderson wrote:
>
>> http://rubyforge.org/pipermail/backgroundrb-devel/2006-June/
>> 000000.html
>> What would be the best way to enable database access for a worker,
>> preferably through ActiveRecord models. Background: I''m trying
to
>> write a worker that periodically gets data from an external source,
>> writes it to the database and is then displayed by Rails.
>
>
> Nobody seems to be answering this problem, so how can we figure out
> how to access an ActiveRecord model class from within a worker?
Ezra did reply, although apparently he did not send his response the
list. Here it is:
[....snip...]
Hello G?nter-
Thanks for the kind words. It''s pretty easy to get access to
ActiveRecord in a worker class. Here is a simple stab at a worker
that can do this:
require ''rubygems''
require ''active_record''
# Set up connection
ActiveRecord::Base.establish_connection(
:adapter => ''mysql'',
:username => ''root'',
:host => ''localhost'',
:password => ''SECRET'',
:database => ''foo_development''
)
# require your model classes from your rails app. Don''t require
observers or notifiers.
Dir["#{RAILS_ROOT}/app/models/**/*.rb"].each do |file|
require file unless file =~ /_observer\.rb|_notifier\.rb/
end
class WorkerWithAR
include DRbUndumped
def initialize(args)
@args = args
start_working
end
def start_working
Thread.new do
# do something with your model classes here.
foo = MyModel.find(args[0])
end
end
end
Something like that will work for what you are trying to do. BUt
maybe you need to explain your problem a little bit more. You want
this worker to do things at times intervals? Or on command from your
rails app? If it is timed intervals and you are just writing to the
database then you may not need backgroundrb. You could get away with
a ruby script and cron. If you let me know a little more detail about
what it is you are trying to accomplish, maybe I can suggest some
other design patterns for you.
Cheers-
-EZra
[...snip...]
Works for me :) You can modify it to load the database configuration
from config/database.yml (although you have to change the environment
manually, I''m afraid):
require ''yaml''
@rails_config = YAML::load(File.open("#{RAILS_ROOT}/config/
database.yml"))
ActiveRecord::Base.establish_connection(
:adapter =>
@rails_config[''development''][''adapter''],
:username =>
@rails_config[''development''][''username''],
:host =>
@rails_config[''development''][''host''],
:password =>
@rails_config[''development''][''password''],
:database =>
@rails_config[''development''][''database'']
)
ciao,
G?nter