Creating a variable directly after rails server loads

45 views Asked by At

I am trying to utilize the classifier gem to classify quotes as either "happy" or "sad". Right now, I have the app configured such that any new POST requests train the classifier by using the following command bayes.train_happy "I am very happy" in app/controllers/quotes_controller.rb

This works whenever adding new quotes while the server is running. However, whenever the server either shuts down or restarts (constantly during development), the variables bayes gets deleted, such that when I restart the server the quotes are saved in the database, but bayes becomes empty.

Essentially, I want to be able to call the following block of code directly after the server starts, such that a user can call the classifier that has already been built directly after the server starts.

bayes = Classifier::Bayes.new 'happy', 'sad'

Quote.all.each do |quote|
    eval("bayes.train_#{quote.classification} quote.body.upcase")
    puts "wrote {#{quote.body}} to bayes"
end

where Quote is defined as the following in db/schema.rb

create_table "quotes", force: true do |t|
    t.string   "body"
    t.string   "classification"
    t.datetime "created_at"
    t.datetime "updated_at"
end
1

There are 1 answers

2
Avdept On BEST ANSWER

Create any file in initializers folder and put your code there. Make sure you have all dependencies included if any. Rails will load and execute it during server loading