Hey we have a library class (lib/Mixpanel) that calls delayed job as follows:
class Mixpanel
attr_accessor :options
attr_accessor :event
def track!()
..
dj = send_later :access_api # also tried with self.send_later
..
end
def access_api
..
end
The problem is that when we run rake jobs:work: we get the following error:
undefined method `access_api' for #<YAML::Object:0x24681b8>
Any idea why?
Delayed_job always autoloads ActiveRecord classes, but it doesn't know about other types of classes (like lib) that it has marshaled in the db as YML. So, you need to explicitly trigger the class loader for them. Since DJ starts up the Rails environment, just mention any non-AR marshaled classes in an initializer:
(config/initializers/load_classes_for_dj.rb)
Mixpanel
A small gotcha, I followed Jonathan's suggestion, but I needed to add a require before the class name, so I'd use this for load_classes_for_dj.rb:
require 'mixpanel'
Mixpanel
Then it worked fine!
Related
I am using Rails 4 w/ the impressionist and resque gem.
I am using impressionist to log unique session hits on my article show page. Due to performance issues and no need to display hits to users (it is for admins only), I would like to move logging impressions off into the background.
Normally I would log an impression using impressionist(#article, unique: [:session_hash]) but to move it off into the bg via resque I am now doing something like this...
articles_controller:
def show
.
.
.
Resque.enqueue(ImpressionLogger, #article.id)
end
app/workers/impression_logger.rb:
class ImpressionLogger
#queue = :impression_queue
def self.perform(article_id)
article = Article.find(article_id)
impressionist(article, unique: [:session_hash])
end
end
When I set it up like this, when resque tries to process the job, it is returning undefined method "impressionist" for ImpressionLogger:Class. What do you guys think the best way to go about this is? I am not sure how to include impressionist methods inside of my resque worker.
The issue
Your problem stems from the fact that it looks like Impressionist works on the controller level due to including a module with the impressionist method in an engine initializer on any instances of ActionController:
https://github.com/charlotte-ruby/impressionist/blob/master/lib/impressionist/engine.rb#L11
You're trying to call the impressionist method from a regular class being invoked in a Resque job, so it's not going to have that method defined.
Solution
It's kind of gross, but if you really want to use impressionist, we can delve into this... Looking at the actual implementation of the impressionist method found here, we see the following:
def impressionist(obj,message=nil,opts={})
if should_count_impression?(opts)
if obj.respond_to?("impressionable?")
if unique_instance?(obj, opts[:unique])
obj.impressions.create(associative_create_statement({:message => message}))
end
else
# we could create an impression anyway. for classes, too. why not?
raise "#{obj.class.to_s} is not impressionable!"
end
end
end
Assuming that you'd be calling something like this manually (as you want to from a resque job) the key are these three lines:
if unique_instance?(obj, opts[:unique])
obj.impressions.create(associative_create_statement({:message => message}))
end
The if wrapper only seems to be important if you want to implement this functionality. Which it looks like you do. The call to associative_create_statement seems to be pulling parameters based off of the controller name as well as parameters passed from Rack such as the useragent string and ip address (here). So, you'll have to resolve these values prior to invoking the Resque job.
What I would suggest at this point is implementing a Resque class that takes in two parameters, an article_id and the impression parameters that you want. The resque class would then just directly create the impression on the impressionable object. Your Resque class would become:
class ImpressionLogger
#queue = :impression_queue
def self.perform(article_id, impression_params = {})
article = Article.find(article_id)
article.impressions.create(impression_params)
end
end
And your controller method would look something like this:
def show
.
.
.
Resque.enqueue(ImpressionLogger, #article.id, associative_create_statement({message: nil})) if unique_instance?(#article, [:session_hash])
end
Disclaimer
There's a fairly big disclaimer that comes with doing it this way though... the method associative_create_statement is marked protected and unique_instance? is marked private... so neither of these is part of the impressionist gem's public API, so this code might break between versions of the gem.
Is impressionist installed properly with bundler? If so Rails should be loading it into your environment. I would check whether you can access impressionist functionality elsewhere in your Rails code (i.e. without going through Resque) as the first step to debugging this.
How are you starting your resque workers? If you need your Rails environment loaded, try rake environment resque:work.
https://github.com/resque/resque/wiki/FAQ#how-do-i-ensure-my-rails-classesenvironment-is-loaded
How to successfully inherit ActiveRecord::Base?
Environment: Ruby 2.0.0, Rails 4.0.3, Windows 8.1, PostreSQL 9.3.3, Devise 3.2.4
I have an operational app and would like to add a comprehensive logging class to it. This will be a complex class that not only logs messages but also creates an SQL database that logs transactions by object. I need this class available throughout all of the classes in the application.
To do this, I wanted to inherit ActiveRecord::Base into the class and then have all other classes inherit it, though I don't plan to use STI. That seemed to be a lot simpler in concept than in practice, even though I thought such inheritance was a common best practice. Am I missing something?
One of the initial tables was this:
class Device < ActiveRecord::Base
...
end
I set it up like this:
class XLog < ActiveRecord::Base
self.abstract_class = true
def initialize
end
end
class Device < XLog
...
end
Prior to this change, the app was working fine. After this change, when I login I receive:
ArgumentError at /devices/sign_in
wrong number of arguments (1 for 0)
The error occurs in:
bin/rails, line 4
bin/rails is:
#!/usr/bin/env ruby.exe
APP_PATH = File.expand_path('../../config/application', __FILE__)
require_relative '../config/boot'
require 'rails/commands'
Device is the Devise "User" class in this application and the error occurs when I try to login. If I change Device to inherit ActiveRecord::Base, it lets me login and run.
But, then I get another error whenever I call "new" on the other classes:
undefined method `[]' for nil:NilClass
I am definitely missing something when it comes to this inheritance. Advice appreciated.
The initialize method was throwing the error. It was triggering every time a subclass was initialized and was configured to accept 0 parameters. When I removed it, the whole thing started working. If I need it, I'll have to configure it to accept a variable number of parameters and pass them as expected, I guess.
i'm using the resque and resque-send-later PLUGINS (not gems) in my project.
I haven't put 'require' statements anywhere in the code at all (since they're plugins and so they must be included upon initialization).
the app is working perfectly locally, but on heroku, it shows an error
"const_missing: unitialized constant User::Resque"
my User model:
class User < ActiveRecord::Base
include Resque::Plugins::SendLater
def self.testingWorker1
# code to be run in the background
end
end
my User_controller: (where i'm calling the above method from)
class UserController < ApplicationController
def testingResqueWorker
User.send_later(:testingWorker1)
end
end
so I removed the line include Resque::Plugins::SendLater from the my model
it still works perfectly locally, but now on heroku it gives an error saying "method_missing: send_later"
my question is:
1. how do we 'include' or 'require' plugins in rails? are they automatically available to all controllers and models?
2. any ideas for how to fix the above errors?
Two thoughts
any reason why you aren't using the gems?
are you sure the plugins have been added to the git repository and therefore have been deployed to heroku?
I am running a delayed job worker. When ever I invoke the foo method, worker prints hello.
class User
def foo
puts "Hello"
end
handle_asynchronously :foo
end
If I make some changes to the foo method, I have to restart the worker for the changes to reflect. In the development mode this can become quite tiresome.
I am trying to find a way to reload the payload class(in this case User class) for every request. I tried monkey patching the DelayedJob library to invoke require_dependency before the payload method invocation.
module Delayed::Backend::Base
def payload_object_with_reload
if Rails.env.development? and #payload_object_with_reload.nil?
require_dependency(File.join(Rails.root, "app", "models", "user.rb"))
end
#payload_object_with_reload ||= payload_object_without_reload
end
alias_method_chain :payload_object, :reload
end
This approach doesn't work as the classes registered using require_dependency needs to be reloaded before the invocation and I haven't figured out how to do it. I spent some time reading the dispatcher code to figure out how Rails reloads the classes for every request. I wasn't able to locate the reload code.
Has anybody tried this before? How would you advise me to proceed? Or do you have any pointers for locating the Rails class reload code?
I managed to find a solution. I used ActiveSupport::Dependencies.clear method to clear the loaded classes.
Add a file called config/initializers/delayed_job.rb
Delayed::Worker.backend = :active_record
if Rails.env.development?
module Delayed::Backend::Base
def payload_object_with_reload
if #payload_object_with_reload.nil?
ActiveSupport::Dependencies.clear
end
#payload_object_with_reload ||= payload_object_without_reload
end
alias_method_chain :payload_object, :reload
end
end
As of version 4.0.6, DelayedJob reloads automatically if Rails.application.config.cache_classes is set to false:
In development mode, if you are using Rails 3.1+, your application code will automatically reload every 100 jobs or when the queue finishes. You no longer need to restart Delayed Job every time you update your code in development.
This looks like it solves your problem without the alias_method hackery:
https://github.com/Viximo/delayed_job-rails_reloader
Trying to integrate some friendly_id gem functionality on a controller method.
Essentially, I have a Market object, which has its URL created based on a custom method. Since it's based on a custom method, friendly_id won't update the URL when the Market object gets updated. Friendly_id does offer a redo_slugs rake task, but when I call it from within my controller, it tells me that it can't build the task. Running the command outside works just fine.
The code for my controller looks like this:
require 'rake'
require 'friendly_id'
class Admin::MarketsController < ApplicationController
def update
if #market.update_attributes(params[:market])
rake_market_slugs
end
end
protected
def rake_market_slugs
Rake::Task["friendly_id:redo_slugs MODEL=Market"].invoke
end
end
Am I missing something? Or can I just not do this inside my controller?
Thank you.
Calling a rake task from a controller to update a model object is terrible. Looking at the code for that rake task, you can see that redo_slugs is simply running the delete_slugs and make_slugs tasks. So there's another reason not to do this. You'll be generating slugs for every Market in your table, instead of just the one that you need.
If you look at the code for make_slugs you can see that there's no magic there. All it does is load your model objects in blocks of 100 and then save them.
So, that would be the first thing I would try. Simply reload and save your model. After that, I'd need to see some logs to dig deeper.
def rake_market_slugs
MODEL="Market"
Rake::Task["friendly_id:redo_slugs"].invoke(MODEL)
end
Try it...