Disable rails class_caching mechanism for Time.now? - ruby-on-rails

I'm currently fighting with the rails class_caching mechanism as I need to return a file path that changes discrete over time. It is used to constantly change a log file path after the amount of GRAIN seconds and returns a fully working timestamp:
GRAIN = 30
def self.file_path
timestamp = (Time.now.to_i / GRAIN) * GRAIN
return FILE_DIR + "tracking_#{timestamp.call}.csv"
end
This works really great if the class_caching of rails is set to false. But of course the app is to run with enabled class caching. And as soon as I enable it, either the timestamp variable is cached or the Time.now expression.
I tried to solve this with a proc block, but no success:
def self.file_path
timestamp = Proc.new { (Time.now.to_i / GRAIN) * GRAIN }
return FILE_DIR + "tracking_#{timestamp.call}.csv"
end
Is there anything like a cache disabled scope I could use or something like skip_class_caching :file_path? Or any other solutions?
Thank you for your help!

It's not entirely clear where your code is located, but ActiveRecord has an uncached method that suspends the cache for whatever is inside its block.

I found the problem. Not the Time.now was beeing cached but a logger instance. It was assigned in another method calling the file_path.
As long as the class caching was disabled the environment forgot about the class variable between the requests. But as soon as it was enabled the class variable stayed the same - and desired value - but never changed.
So I had to add a simple condition that checks if the file_path changed since the last request. If so, the class variable is reassigned, otherwise it keeps the same desired value.
I changed from:
def self.tracker
file_path = Tracking.file_path
##my_tracker ||= Logger.new(file_path)
end
to:
def self.tracker
file_path = Tracking.file_path
##my_tracker = Logger.new(file_path) if ##my_tracker.nil? or Tracking.shift_log?(file_path)
##my_tracker
end
Thank you for your help anyways!

Related

How can I make this method more concise?

I get a warning when running reek on a Rails project:
[36]:ArborReloaded::UserStoryService#destroy_stories has approx 8 statements (TooManyStatements)
Here's the method:
def destroy_stories(project_id, user_stories)
errors = []
#project = Project.find(project_id)
user_stories.each do |current_user_story_id|
unless #project.user_stories.find(current_user_story_id).destroy
errors.push("Error destroying user_story: #{current_user_story_id}")
end
end
if errors.compact.length == 0
#common_response.success = true
else
#common_response.success = false
#common_response.errors = errors
end
#common_response
end
How can this method be minimized?
First, I find that class and method size are useful for finding code that might need refactoring, but sometimes you really do need a long class or method. And there is always a way to make your code shorter to get around such limits, but that might make it less readable. So I disable that type of inspection when using static analysis tools.
Also, it's unclear to me why you'd expect to have an error when deleting a story, or who benefits from an error message that just includes the ID and nothing about what error occurred.
That said, I'd write that method like this, to reduce the explicit local state and to better separate concerns:
def destroy_stories(project_id, story_ids)
project = Project.find(project_id) # I don't see a need for an instance variable
errors = story_ids.
select { |story_id| !project.user_stories.find(story_id).destroy }.
map { |story_id| "Error destroying user_story: #{story_id}" }
respond errors
end
# Lots of services probably need to do this, so it can go in a superclass.
# Even better, move it to #common_response's class.
def respond(errors)
# It would be best to move this behavior to #common_response.
#common_response.success = errors.any?
# Hopefully this works even when errors == []. If not, fix your framework.
#common_response.errors = errors
#common_response
end
You can see how taking some care in your framework can save a lot of noise in your components.

WoW Weakauras Custom Tricker

I am trying to get a trigger that will show with the sunfire debuff has less time then my nature's grace buff. the lua calls seem to be pulling the correct number, but it is constantly returning true?
function ()
_,_,_,_,_,_,sundur= UnitDebuff("target","Sunfire","player");
_,_,_,_,_,_,NGDur= UnitAura("player","Nature's Grace");
if sundur and NGDur then
if sundur<NGDur+2 then
return true
else
return false
end
end
end
The issue i found was that the ad don was allowing the declared variables to be saved globally which was causing it not to be updated properly even as i changed them. I also had to change one part of code, removing the "" around player only on the uniteDebuff "caster" filter.
local _,_,_,_,_,_,sundur= UnitDebuff("target","Sunfire",player);

Not able to hit mixpanel in delayed job?

I am using delayed_job to do some background task. In between I want to track some events. I am using mixpanel gem to track the events. In controller its working perfectly fine. But not in Delayed Job.
Code I am using
#original_message = Message.find(message_id)
#mixpanel= Mixpanel::Tracker.new("43242637426346287482", message_id, true)
#mixpanel.track_event("blank_body", {:reset_result => "sucess" })
//message_id is a unique for every request.
I have specified
gem 'mixpanel' in gemfile
{undefined method `[]=' for 45:Fixnum
/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/mixpanel-0.9.0/lib/mixpanel/tracker.rb:38:in clear_queue'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/mixpanel-0.9.0/lib/mixpanel/tracker.rb:13:ininitialize'\n/Users/mohit/projects/textadda/lib/message_job.rb:109:in new'\n/Users/mohit/projects/textadda/lib/message_job.rb:109:inperform'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/delayed_job-2.1.4/lib/delayed/backend/base.rb:87:in invoke_job'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/delayed_job-2.1.4/lib/delayed/worker.rb:120:inrun'\n/Users/mohit/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/timeout.rb:67:in timeout'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/delayed_job-2.1.4/lib/delayed/worker.rb:120:inrun'\n/Users/mohit/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/benchmark.rb:308:in realtime'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/delayed_job-2.1.4/lib/delayed/worker.rb:119:inrun'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/delayed_job-2.1.4/lib/delayed/worker.rb:177:in reserve_and_run_one_job'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/delayed_job-2.1.4/lib/delayed/worker.rb:104:inwork_off'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/delayed_job-2.1.4/lib/delayed/worker.rb:103:in times'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/delayed_job-2.1.4/lib/delayed/worker.rb:103:inwork_off'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/delayed_job-2.1.4/lib/delayed/worker.rb:78:in start'\n/Users/mohit/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/benchmark.rb:308:inrealtime'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/delayed_job-2.1.4/lib/delayed/worker.rb:77:in start'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/delayed_job-2.1.4/lib/delayed/worker.rb:74:inloop'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/delayed_job-2.1.4/lib/delayed/worker.rb:74:in start'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/delayed_job-2.1.4/lib/delayed/tasks.rb:9\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/task.rb:205:incall'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/task.rb:205:in execute'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/task.rb:200:ineach'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/task.rb:200:in execute'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/task.rb:158:ininvoke_with_call_chain'\n/Users/mohit/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/monitor.rb:242:in synchronize'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/task.rb:151:ininvoke_with_call_chain'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/task.rb:144:in invoke'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/application.rb:112:ininvoke_task'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/application.rb:90:in top_level'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/application.rb:90:ineach'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/application.rb:90:in top_level'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/application.rb:129:instandard_exception_handling'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/application.rb:84:in top_level'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/application.rb:62:inrun'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/application.rb:129:in standard_exception_handling'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/lib/rake/application.rb:59:inrun'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/gems/rake-0.9.2/bin/rake:32\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/bin/rake:19:in `load'\n/Users/mohit/.rvm/gems/ruby-1.8.7-p334/bin/rake:19
EDIT
I have implemented mixpanel in background process using standard get request. But I am still looking for the solution how can I use Mixpanel gem in background process.
You should just be doing something like this:
#mixpanel= Mixpanel::Tracker.new("43242637426346287482", {:REMOTE_ADDR => message_id}, true)
#mixpanel.track_event("blank_body", {:reset_result => "sucess" })
The gem expects the second variable to be the request environment, so will get the ip address that way, and send that to mixpanel.com. But I am not even sure if that is really needed, so I think that even a simple
#mixpanel= Mixpanel::Tracker.new("43242637426346287482", {}, true)
#mixpanel.track_event("blank_body", {:reset_result => "sucess" })
should work.
Hope this helps.
NOTE: THIS ANSWER IS NOW OUT OF DATE AS OF OCT 15 2012 AS THE INITIALIZE METHOD NO LONGER TAKES A ENV PARAMETER
The example on https://github.com/zevarito/mixpanel Mixpanel::Tracker.new gets called like this:
Mixpanel::Tracker.new("YOUR_MIXPANEL_API_TOKEN", request.env, true)
In a controller context, request.env is a hash.
In your code above your passing in message_id as the second argument, which looks like an integer. Sorry, can't help anymore than that, don't know anything about the mixpanel gem, but that's the root of your problem.
If the mixpanel API documentation tells you you can pass an integer as the second parameter, it's incorrect. Here's the code relevant to your error from https://github.com/zevarito/mixpanel/blob/master/lib/mixpanel/tracker.rb
module Mixpanel
class Tracker
def initialize(token, env, async = false)
#token = token
#env = env
#async = async
clear_queue
end
# snip
def clear_queue
#env["mixpanel_events"] = []
end
# snip
end
end
Passing an integer as the second argument to the initializer will not work, because the Fixnum class doesn't have a hash assignment ([]=) method, which is exactly the error message you are getting.
If the documentation tells you this can be an integer, you should probably file an issue against mixpanel.

find_or_create and race-condition in rails, theory and production

Hi I've this piece of code
class Place < ActiveRecord::Base
def self.find_or_create_by_latlon(lat, lon)
place_id = call_external_webapi
result = Place.where(:place_id => place_id).limit(1)
result = Place.create(:place_id => place_id, ... ) if result.empty? #!
result
end
end
Then I'd like to do in another model or controller
p = Post.new
p.place = Place.find_or_create_by_latlon(XXXXX, YYYYY) # race-condition
p.save
But Place.find_or_create_by_latlon takes too much time to get the data if the action executed is create and sometimes in production p.place is nil.
How can I force to wait for the response before execute p.save ?
thanks for your advices
You're right that this is a race condition and it can often be triggered by people who double click submit buttons on forms. What you might do is loop back if you encounter an error.
result = Place.find_by_place_id(...) ||
Place.create(...) ||
Place.find_by_place_id(...)
There are more elegant ways of doing this, but the basic method is here.
I had to deal with a similar problem. In our backend a user is is created from a token if the user doesn't exist. AFTER a user record is already created, a slow API call gets sent to update the users information.
def self.find_or_create_by_facebook_id(facebook_id)
User.find_by_facebook_id(facebook_id) || User.create(facebook_id: facebook_id)
rescue ActiveRecord::RecordNotUnique => e
User.find_by_facebook_id(facebook_id)
end
def self.find_by_token(token)
facebook_id = get_facebook_id_from_token(token)
user = User.find_or_create_by_facebook_id(facebook_id)
if user.unregistered?
user.update_profile_from_facebook
user.mark_as_registered
user.save
end
return user
end
The step of the strategy is to first remove the slow API call (in my case update_profile_from_facebook) from the create method. Because the operation takes so long, you are significantly increasing the chance of duplicate insert operations when you include the operation as part of the call to create.
The second step is to add a unique constraint to your database column to ensure duplicates aren't created.
The final step is to create a function that will catch the RecordNotUnique exception in the rare case where duplicate insert operations are sent to the database.
This may not be the most elegant solution but it worked for us.
I hit this inside a sidekick job that retries and gets the error repeatedly and eventually clears itself. The best explanation I've found is on a blog post here. The gist is that postgres keeps an internally stored value for incrementing the primary key that gets messed up somehow. This rings true for me because I'm setting the primary key and not just using an incremented value so that's likely how this cropped up. The solution from the comments in the link above appears to be to call ActiveRecord::Base.connection.reset_pk_sequence!(table_name) This cleared up the issue for me.
begin
result = Place.where(:place_id => place_id).limit(1)
result = Place.create(:place_id => place_id, ... ) if result.empty? #!
rescue ActiveRecord::StatementInvalid => error
#save_retry_count = (#save_retry_count || 1)
ActiveRecord::Base.connection.reset_pk_sequence!(:place)
retry if( (#save_retry_count -= 1) >= 0 )
raise error
end

How do I temporarily monkey with a global module constant?

Greetings,
I want to tinker with the global memcache object, and I found the following problems.
Cache is a constant
Cache is a module
I only want to modify the behavior of Cache globally for a small section of code for a possible major performance gain.
Since Cache is a module, I can't re-assign it, or encapsulate it.
I Would Like To Do This:
Deep in a controller method...
code code code...
old_cache = Cache
Cache = MyCache.new
code code code...
Cache = old_cache
code code code...
However, since Cache is a constant I'm forbidden to change it. Threading is not an issue at the moment. :)
Would it be "good manners" for me to just alias_method the special code I need
just for a small section of code and then later unalias it again? That doesn't
pass the smell test IMHO.
Does anyone have any ideas?
TIA,
-daniel
But you can overwrite constants in Ruby (regardless of whether it's a module or class or simple other object):
MyConst = 1
# do stuff...
old_my_const = MyConst
MyConst = 5
puts "MyConst is temporarily #{MyConst}"
MyConst = old_my_const
puts "MyConst is back to #{MyConst}"
Output:
a.rb:6: warning: already initialized constant MyConst
MyConst is temporarily 5
a.rb:8: warning: already initialized constant MyConst
MyConst is back to 1
The warnings are simply that: warnings. Your code will continue to run the same.
Okay, maybe the warnings are unacceptable in your situation for some reason. Use this suppress_all_warnings method I've written. Example includes reassigning a module.
def suppress_all_warnings
old_verbose = $VERBOSE
begin
$VERBOSE = nil
yield if block_given?
ensure
# always re-set to old value, even if block raises an exception
$VERBOSE = old_verbose
end
end
module OriginalModule
MyConst = 1
end
module OtherModule
MyConst = 5
end
def print_const
puts OriginalModule::MyConst
end
print_const
suppress_all_warnings do
old_module = OriginalModule
OriginalModule = OtherModule
print_const
OriginalModule = old_module
end
print_const
Now you get the correct output, but without the warnings:
1
5
1

Resources