Ruby debugger: weird sort of caching - ruby-on-rails

I'm using Ruby debugger gem in my RoR project. Ruby 1.9.3 and Rails 3.2
Debugger works fine by a sort of weird file caching occurs.
I mean:
First example
[4, 13] in /.../app/controllers/fork_controller.rb
4 def index
5
6 debugger
7 a = "hello"
8
=> 9 puts "#{a}"
10
11 end
12
13 def requesting
(rdb:4) eval a
"hello"
(rdb:4) continue
Then I change var "a" to "hello2"
def index
debugger
a = "hello2"
puts "#{a}"
end
this is the result:
[4, 13] in /.../app/controllers/fork_controller.rb
4 def index
5
6 debugger
7 a = "hello"
8
=> 9 puts "#{a}"
10
11 end
12
13 def requesting
(rdb:4) eval a
"hello2"
(rdb:4) continue
So ... the variable evaluation is correct "hello2" instead of "hello" but ... the "breakpoint view" show the first variable content "hello".
What is wrong?
Thanks in advance.

Related

Pass Params from select_tag in rails to one script.rb get this params

Hello how is it possible to pass web parameters to an rb script in rails?
I'm using select_tag where when choosing an option I send the value to a variable in script.rb
Could help me I'm studying ruby ​​and rails is very complicated for me to do this.
my controller.rb
#myvalue = ["OPT VALUE 1","OPT VALUE 2"]
my external script.rb
loop do
#give_my_param_from_rails = gets.chomp
case #give_my_param_from_rails
when '1'
puts "i get number 1"
when '2'
puts "i get number 2"
else
puts "dont get any value"
break
end
end
my html.erb
<%= select_tag "my_options", options_for_select(#myvalue) %>
In my external script I want the rails value selected in select_tag to be set in the #give_my_param_from_rails variable help me?
I've added $stdout.flush to the end of your script to flush the output for each line of input:
loop do
line = gets.chomp
case line
when '1'
puts "i get number 1"
when '2'
puts "i get number 2"
else
puts "dont get any value"
break
end
$stdout.flush # flush output after each line of input
end
To access the script in your controller you can now do:
# allow writing to io by using r+ mode
# https://ruby-doc.org/core-2.6.5/IO.html#method-c-new-label-IO+Open+Mode
File.popen('ruby /path/to/script.rb', 'r+') do |io|
io.puts params[:my_options] # assuming params[:my_options] is "1"
io.gets #=> "i get number 1\n"
io.puts 2
io.gets #=> "i get number 2\n"
io.puts "foo bar" # falling in the else scenario breaks the loop, exiting the script
io.gets #=> "dont get any value\n"
io.puts 1
io.gets #=> nil
io.puts "foo bar"
io.gets #=> nil
end
If you only need to supply one input you could use backticks instead:
input = params[:my_options] # assuming params[:my_options] is "foo bar"
# escape special characters in double quoted context
# https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
sanatized_input = input.gsub(/([$`\\"])/, '\\\\\1')
output = `echo "${sanatized_input}" | ruby /path/to/script.rb`
#=> "dont get any value\n"
Keep in mind that you don't handle the scenario where you supply 1 or 2 and then close the input. When this happens the next gets call will return nil.
`echo 1 | ruby /path/to/script.rb`
# script.rb:2:in `block in <main>': undefined method `chomp' for nil:NilClass (NoMethodError)
# from script.rb:1:in `loop'
# from script.rb:1:in `<main>'
#=> "i get number 1\n"
To resolve this you could do something like:
loop do
line = gets or break # break the loop if gets returns nil
line.chomp!
# ...
end

Ruby on rails tests

In controller I have got this:
def output
if params[:find]
result
elsif params[:print_db]
print_db
end
end
And the test doesn't want to enter in params[:find] condition.
Test controller:
test "should get 5 5 1 for view with 5 5 1 3 3" do
get :output, {str: "5 5 1 3 3 5"}, :params => 'find'
assert_equal assigns[:result], "5, 5, 1"
end
Please, help me!
It seems like you want to have both: A params[:str] and a params[:find] parameter.
Change:
get :output, {str: "5 5 1 3 3 5"}, :params => 'find'
to:
get :output, str: '5 5 1 3 3 5', find: true
Because your version passes the :params => 'find' part into the session variable not into the params. You might want to read in the Rails' guide about what parameters the get method accepts.
Try this:
get :output, { str: "5 5 1 3 3 5", find: true }
In your request you send only the str with the value "5 5 1 3 3 5" and no find parameter. You have to put all parameters into the first hash.

Is there a "spawn" equivalent for Ruby 1.8.7?

Is there a spawn equivalent for ruby 1.8.7?
It appears as though it was introduced in 1.9.1
http://apidock.com/ruby/Kernel/spawn
I need the following to work in ruby 1.8.7:
def run_worker(queue, count = 1)
puts "Starting #{count} worker(s) with QUEUE: #{queue}"
ops = {:pgroup => true, :err => [(Rails.root + "log/resque_err").to_s, "a"],
:out => [(Rails.root + "log/resque_stdout").to_s, "a"]}
env_vars = {"QUEUE" => queue.to_s}
count.times {
## Using Kernel.spawn and Process.detach because regular system() call would
## cause the processes to quit when capistrano finishes
pid = spawn(env_vars, "rake resque:work", ops)
Process.detach(pid)
}
end
You can achieve this in 1.8.7 using this gem - https://github.com/rtomayko/posix-spawn.
It does not support "full" 1.9's Process::spawn interface, but your example should work with it just by changing Process::spawn to POSIX::Spawn::spawn (https://github.com/rtomayko/posix-spawn#status).

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

Delayed_Job executing rake not redirecting output

I have a class which is currently being executed via delayed job. One of the tasks is to execute "rake spec" and redirect the output.
I do this as such:
class Executor
def execute_command(cmd, &block)
STDOUT.sync = true # That's all it takes...
IO.popen(cmd + " 2>&1") do |pipe| # Redirection is performed using operators
pipe.sync = true
while str = pipe.gets
block.call str # This is synchronous!
end
end
return $?.success?
end
end
However, none of the output appears and it doesn't even aware to execute the unit tests correctly.
Capistrano works and it works on OSX. My server is Ubuntu running Passenger.
Anyone have any ideas why the output wouldn't be redirecting?
Thanks
Ben
Try without the STDFDES redirection on cmd
here is what i used and what i get.
class Executor
def execute_command(cmd, &block)
STDOUT.sync = true # That's all it takes...
IO.popen(cmd) do |pipe| # Redirection is performed using operators
pipe.sync = true
while str = pipe.gets
block.call str # This is synchronous!
end
end
return $?.success?
end
end
Tested with:
ex = Executor.new
ex.execute_command "ps aux" do |str|
p str
end
result:
"USER PID %CPU %MEM VSZ RSS TT STAT STARTED
TIME COMMAND\n" "mitch 423 3.4 1.0 2750692 159552 ??
S 23Apr12 19:41.59 /Users/mitch/iTerm.app/Contents/MacOS/iTerm
-psn_0_40970\n" "_windowserver 90 3.1 1.8 3395124 301576 ?? Ss 20Apr12 75:19.86
/System/Library/Frameworks/ApplicationServices.framework/Frameworks/CoreGraphics.framework/Resources/WindowServer
-daemon\n" "mitch 78896 2.0 0.8 1067248 136088 ?? R Thu03PM 37:46.59 /Applications/Spotify.app/Contents/MacOS/Spotify
-psn_0_4900012\n" "mitch 436 1.8 1.0 1063952 169320 ?? S 23Apr12 100:23.87
/Applications/Skype.app/Contents/MacOS/Skype -psn_0_90134\n"

Resources