"no block given" errors with cache_money - ruby-on-rails

i've inherited a site that in production is generating dozens of "no block given" exceptions every 5 minutes.
the top of the stack trace is:
vendor/gems/nkallen-cache-money-0.2.5/lib/cash/accessor.rb:42:in `add'
vendor/gems/nkallen-cache-money-0.2.5/lib/cash/accessor.rb:33:in `get'
vendor/gems/nkallen-cache-money-0.2.5/lib/cash/accessor.rb:22:in `call'
vendor/gems/nkallen-cache-money-0.2.5/lib/cash/accessor.rb:22:in `fetch'
vendor/gems/nkallen-cache-money-0.2.5/lib/cash/accessor.rb:31:in `get'
so it appears that the problem is in the cache money plugin.
has anyone experienced something similar?
i've cut and pasted the relevant code below -- anyone more familiar with blocks able to discern any obvious problems?
11 def fetch(keys, options = {}, &block)
12 case keys
13 when Array
14 keys = keys.collect { |key| cache_key(key) }
15 hits = repository.get_multi(keys)
16 if (missed_keys = keys - hits.keys).any?
17 missed_values = block.call(missed_keys)
18 hits.merge!(missed_keys.zip(Array(missed_values)).to_hash)
19 end
20 hits
21 else
22 repository.get(cache_key(keys), options[:raw]) || (block ? block.call : nil)
23 end
24 end
25
26 def get(keys, options = {}, &block)
27 case keys
28 when Array
29 fetch(keys, options, &block)
30 else
31 fetch(keys, options) do
32 if block_given?
33 add(keys, result = yield(keys), options)
34 result
35 end
36 end
37 end
38 end
39
40 def add(key, value, options = {})
41 if repository.add(cache_key(key), value, options[:ttl] || 0, options[:raw]) == "NOT_STORED\r\n"
42 yield
43 end
44 end

line 33 is calling add, but not passing a block, though one is expected on line 42 and there's no block_given? check like there is in the get method. There doesn't really seem to be an appropriate block to pass in this case, as the block passed to get is already yielded to in the add call on line 33, so passing it again separately to add is probably not correct.
Changing line 42 to yield if block_given? should fix your error in this case and shouldn't cause problems elsewhere.
It's also worth noting that line 42 is only called if something was not stored, so you may want to look into why that's happening.

Related

ActionController::ParameterMissing when the parameter is there

So I'm getting this error for whatever reason. It says that the parameter "User" is missing, but I can see it pretty clearly there. Also, I'm not sure why the "user" parameter is listed twice with the second being empty, but I assume that's part of what's causing it.
Started POST "/users" for 127.0.0.1 at 2018-08-30 21:56:48 -0700
Processing by UsersController#create as HTML
Parameters: {"params"=>{"user"=>{"username"=>"fsda", "first_name"=>"fdsa", "last_name"=>"fds", "email"=>"fdsa", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}, "headers"=>{"Content-Type"=>"application/json"}, "user"=>{}}
Completed 400 Bad Request in 0ms (ActiveRecord: 0.0ms)
ActionController::ParameterMissing (param is missing or the value is empty: user):
app/controllers/users_controller.rb:18:in `user_params'
app/controllers/users_controller.rb:4:in `create'
Here's the piece of code that's making the call from a separate server (React client)
25 ax.post('/users', { |~
26 params: { |~
27 user: this.state |~
28 }, |~
29 headers: { |~
30 "Content-Type": 'application/json' |~
31 } |~
32 })
ax is defined here in a separate file:
1 import axios from 'axios';
2
3 export default axios.create({
4 baseURL: 'http://localhost:3000'
5 })
And here's the Rails controller
3 def create
4 #user.new(user_params)
5 if #user.save
6 json_response(#user, :created)
7 end
8 end
9
10 def show
11 #user = User.find(params[:id])
12 render json: #user
13 end
14
15 private
16
17 def user_params
18 params.require(:user).permit(:username, :email, :first_name, :last_name, :password_digest)
19 end
Sorry about the poor formatting. Copy-pasting from vim is really awkward unless someone knows a better way to do that.
SOLUTION:
Change #user.new(user_params) to #user = User.new(user_params
Change params: { user: {...} } to user: {...}

unsupported: Symbol in Cucumber on Rails

I am trying to call each on an ActiveRecord object/list in RoR as shown in the following chunk of code.
41 Then /I should (not )?see movies with ratings: (.*)/ do |not_see, rating_li>
42 #movies = Movie.where(:rating, rating_list.split(", "))
43 rating_list.split(",").map do |x|
44 x.strip
45 end.each do |rating|
46 if not_see
47 #movies.each do |movie|
48 #movie.title
49 end
50 else
51 puts "hello"
52 end
53 end
54 end
And this produces the following error message:
And I should not see movies with ratings: G, PG-13, NC-17 # features/step_definitions/movie_steps.rb:41
unsupported: Symbol (RuntimeError)
./features/step_definitions/movie_steps.rb:47:in `block (2 levels) in <top (required)>'
./features/step_definitions/movie_steps.rb:45:in `each'
./features/step_definitions/movie_steps.rb:45:in `/I should (not )?see movies with ratings: (.*)/'
features/filter_movie_list.feature:33:in `And I should not see movies with ratings: G, PG-13, NC-17'
Removing line 47 in the code above gets rid of the error. Why is that? As far as I can tell, all of these are valid Ruby code. What am I missing?
Thank you all!
The line of code that was causing the error is line 42. The call to where should have been:
Movie.where(:rating => rating_list.split(","))
"=>" and not ","

Deleting singleton object and reconstructing in ruby

I've this situation wherein a singleton class creates object of a model and is used further in my code.
Now, the problem is that occasionally the connection between application and database is broken and all subsequent calls to the singleton fail. While I'm working on fixing the issue, a workaround is required immediately. I believe the solution I'm thinking of, would work but not sure if it will leak memory, cause deadlocks etc.
Here's the original (partial) code:
1 file_path = File.expand_path(File.dirname(__FILE__))
2 require file_path + '/action_factory'
3 require 'erb'
4
5 class Manager
6
7 def initialize(logger)
8 #logger = logger
9 end
10
11 def log_exception(e,method_name)
12 #logger.log :ERROR,"Manager",method_name,'',$$,'',e.backtrace[0] + ": Uncaught Exception " + e.message,DateTime.now,'system',''
13 e.backtrace.shift
14 #logger.log :ERROR,"Manager",method_name,'',$$,''," from " + e.backtrace.join("\n from ") + "(" + e.class.to_s + ")",DateTime.now,'system',''
15 end
16 def execute_action
17 return false if addresses.collect{|a| a if !a.to_s.empty?}.compact.empty?
18 begin
19 action = ActionFactory.instance().get_action(type)
20 return true
21 rescue Exception => e
22 action = nil ####### I'm planning to add this line ####
23 log_exception(e,this_method_name)
24 return false
25 end
26 end
27 end
28 require 'singleton'
29 $file_path=File.expand_path(File.dirname(__FILE__))
30 Dir[$file_path + '/actions/*_action.rb'].each { |filename| require filename }
31
32 class ActionFactory
33 include Singleton
34
35 def get_action(type)
36 action_type_obj = ActionType.find(:first, :select => "action_name", :conditions => ["id=?",type])
37 if(action_type_obj.nil? or action_type_obj.action_name.nil?)
38 raise "Undefined Action Type"
39 else
40 return eval("Actions::#{action_type_obj.action_name}").instance
41 end
42 end
43 end
The problem is that oracle connection is disconnected sometimes and the statement #36 fails returning InvalidStatement exception. All subsequent calls of the statement 19 fail.
I'm planning to add a statement : action = nil in the exception block in line 22. Will that suffice as a workaround or would it bring more issues like memory leakages, deadlocks etc?
If there is a better solution, I'll be glad to hear.
Thanks

Ruby expression evaluation: whitespace matters?

Imagine it's Jan 19. This will not be hard if you look at this question today.
Date.today
=> Thu, 19 Jan 2012 # as expected
Date.today + 1
=> Fri, 20 Jan 2012 # as expected
Date.today+1
=> Fri, 20 Jan 2012 # as expected
Date.today +1
=> Thu, 19 Jan 2012 # ?!
What am I missing here?
The difference is that:
Date.today + 1
is an addition of two numerical values and
Date.today +1
is a call to the method today with the parameter sg(day of calendar reform) with value +1
The best way to examine this is to monkey patch the original method with debug output included. See this script as example:
require 'date'
class Date
def self.today(sg=ITALY)
puts "ITALY default("+sg.to_s+")" if sg==ITALY
puts sg unless sg==ITALY
jd = civil_to_jd(*(Time.now.to_a[3..5].reverse << sg))
new0(jd_to_ajd(jd, 0, 0), 0, sg)
end
end
puts "- Addition:"
Date.today + 1
puts "- Parameter:"
Date.today +1
This will print the following console output:
- Addition:
ITALY default(2299161)
- Parameter:
1
Yes, whitespace does matter in Ruby, contrary to popular belief. For example, foo bar is not the same as foobar.
In this particular case,
Date.today + 1
is the same as
Date.today().+(1)
Whereas
Date.today +1
is the same as
Date.today(+1)
which is the same as
Date.today(1.+#())

Add seconds (in fixnum format) to a datetime, Rails

I need to pass a variable to my view with Time.now + #seconds in time format (i.e. 12pm + 3600 seconds = 1:00pm, which goes to the view).
Time.now + #seconds #seconds is a fixnum
doesn't work because "Time can't be coerced into Fixnum". How then can I generate this simple result?
Don't barbeque me if this is wrong now but back when I was doing Rails you would just say Time.now + #seconds.seconds . Also #seconds.seconds.from_now
Today I learned that (1.second + DateTime.now) != (DateTime.now + 1.second)
to answer your question try using Time.now + #seconds.seconds or Time.now + #seconds.to_i.seconds
Another example
DateTime.current + 20.seconds
=> Mon, 11 Jan 2021 18:06:04 +0000

Resources