I have a simple worker that performs methods on some text and stores them in variables. How can I saved this data into the allocated columns?
Controller:
def create
@blog = Blog.new(blog_params)
if @blog.save
Resque.enqueue(Counter, Blog.extract_text)
redirect_to backend_blogs_path, notice: "Success!"
else
render "new"
end
end
Model:
def self.extract_text
Blog.last.text
end
Worker:
class Counter
@queue = :count
def self.perform(*args)
@wordcount = args.count
@@charactercount = args.size
@whitespacecount = args.count(" ")
end
end
As you can see I need to store the data from these three variables into the columns in the database.
create_table "blogs", force: :cascade do |t|
t.string "title"
t.string "text"
t.string "image"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "slug"
t.boolean "active"
t.integer "whitespacecount"
t.integer "charactercount"
t.integer "wordcount"
t.index ["slug"], name: "index_blogs_on_slug", unique: true
end
Do I need to pass them back into the controller?
Instead of passing the text directly to the worker just pass the pass the id of the blog:
# in your controller
def create
@blog = Blog.new(blog_params)
if @blog.save
Resque.enqueue(Counter, @blog.id)
redirect_to backend_blogs_path, notice: "Success!"
else
render "new"
end
end
Then in your worker, load the blog, analyze it and write the database back:
# in the worker
class Counter
@queue = :count
def self.perform(blog_id)
blog = Blog.find(blog_id)
blog.update(
wordcount: blog.text.split(' ').count,
charactercount: blog.text.size,
whitespacecount: blog.text.count(' ')
)
end
end