How to get a stopwatch program running? - ruby
I borrowed some code from a site, but I don't know how to get it to display.
class Stopwatch
def start
#accumulated = 0 unless #accumulated
#elapsed = 0
#start = Time.now
#mybutton.configure('text' => 'Stop')
#mybutton.command { stop }
#timer.start
end
def stop
#mybutton.configure('text' => 'Start')
#mybutton.command { start }
#timer.stop
#accumulated += #elapsed
end
def reset
stop
#accumulated, #elapsed = 0, 0
#mylabel.configure('text' => '00:00:00.00.000')
end
def tick
#elapsed = Time.now - #start
time = #accumulated + #elapsed
h = sprintf('%02i', (time.to_i / 3600))
m = sprintf('%02i', ((time.to_i % 3600) / 60))
s = sprintf('%02i', (time.to_i % 60))
mt = sprintf('%02i', ((time - time.to_i)*100).to_i)
ms = sprintf('%04i', ((time - time.to_i)*10000).to_i)
ms[0..0]=''
newtime = "#{h}:#{m}:#{s}.#{mt}.#{ms}"
#mylabel.configure('text' => newtime)
end
end
How would I go about getting this running?
Thanks
Based upon the additional code rkneufeld posted, this class requires a timer that is specific to Tk. To do it on the console, you could just create a loop that calls tick over and over. Of course, you have to remove all the code that was related to the GUI:
class Stopwatch
def start
#accumulated = 0 unless #accumulated
#elapsed = 0
#start = Time.now
# #mybutton.configure('text' => 'Stop')
# #mybutton.command { stop }
# #timer.start
end
def stop
# #mybutton.configure('text' => 'Start')
# #mybutton.command { start }
# #timer.stop
#accumulated += #elapsed
end
def reset
stop
#accumulated, #elapsed = 0, 0
# #mylabel.configure('text' => '00:00:00.00.000')
end
def tick
#elapsed = Time.now - #start
time = #accumulated + #elapsed
h = sprintf('%02i', (time.to_i / 3600))
m = sprintf('%02i', ((time.to_i % 3600) / 60))
s = sprintf('%02i', (time.to_i % 60))
mt = sprintf('%02i', ((time - time.to_i)*100).to_i)
ms = sprintf('%04i', ((time - time.to_i)*10000).to_i)
ms[0..0]=''
newtime = "#{h}:#{m}:#{s}.#{mt}.#{ms}"
# #mylabel.configure('text' => newtime)
end
end
watch = Stopwatch.new
watch.start
1000000.times do
puts watch.tick
end
You'll end up with output like this:
00:00:00.00.000
00:00:00.00.000
00:00:00.00.000
...
00:00:00.00.000
00:00:00.00.000
00:00:00.01.160
00:00:00.01.160
...
Not particularly useful, but there it is. Now, if you're looking to do something similar in Shoes, try this tutorial that is very similar.
I believe you have found the example on this site
I'm repeating what is already on the site but you are missing:
require 'tk'
as well as initialization code:
def initialize
root = TkRoot.new { title 'Tk Stopwatch' }
menu_spec = [
[
['Program'],
['Start', lambda { start } ],
['Stop', lambda { stop } ],
['Exit', lambda { exit } ]
],
[
['Reset'], ['Reset Stopwatch', lambda { reset } ]
]
]
#menubar = TkMenubar.new(root, menu_spec, 'tearoff' => false)
#menubar.pack('fill'=>'x', 'side'=>'top')
#myfont = TkFont.new('size' => 16, 'weight' => 'bold')
#mylabel = TkLabel.new(root)
#mylabel.configure('text' => '00:00:00.0', 'font' => #myfont)
#mylabel.pack('padx' => 10, 'pady' => 10)
#mybutton = TkButton.new(root)
#mybutton.configure('text' => 'Start')
#mybutton.command { start }
#mybutton.pack('side'=>'left', 'fill' => 'both')
#timer = TkAfter.new(1, -1, proc { tick })
Tk.mainloop
end
end
Stopwatch.new
I would suggest reading through the rest of the site to understand what is all going on.
I was searching for a quick and dirty stop watch class to avoid coding such and came upon the site where the original code was posted and this site as well.
In the end, I modified the code until it met what I think that I was originally searching for.
In case anyone is interested, the version that I have ended up thus far with is as follows (albeit that I have yet to apply it in the application that I am currently updating and for which I want to make use of such functionality).
# REFERENCES
# 1. http://stackoverflow.com/questions/858970/how-to-get-a-stopwatch-program-running
# 2. http://codeidol.com/other/rubyckbk/User-Interface/Creating-a-GUI-Application-with-Tk/
# 3. http://books.google.com.au/books?id=bJkznhZBG6gC&pg=PA806&lpg=PA806&dq=ruby+stopwatch+class&source=bl&ots=AlH2e7oWWJ&sig=KLFR-qvNfBfD8WMrUEbVqMbN_4o&hl=en&ei=WRjOTbbNNo2-uwOkiZGwCg&sa=X&oi=book_result&ct=result&resnum=8&ved=0CEsQ6AEwBw#v=onepage&q=ruby%20stopwatch%20class&f=false
# 4. http://4loc.wordpress.com/2008/09/24/formatting-dates-and-floats-in-ruby/
module Utilities
class StopWatch
def new()
#watch_start_time = nil #Time (in seconds) when the stop watch was started (i.e. the start() method was called).
#lap_start_time = nil #Time (in seconds) when the current lap started.
end #def new
def start()
myCurrentTime = Time.now() #Current time in (fractional) seconds since the Epoch (January 1, 1970 00:00 UTC)
if (!running?) then
#watch_start_time = myCurrentTime
#lap_start_time = #watch_start_time
end #if
myCurrentTime - #watch_start_time;
end #def start
def lap_time_seconds()
myCurrentTime = Time.now()
myLapTimeSeconds = myCurrentTime - #lap_start_time
#lap_start_time = myCurrentTime
myLapTimeSeconds
end #def lap_time_seconds
def stop()
myTotalSecondsElapsed = Time.now() - #watch_start_time
#watch_start_time = nil
myTotalSecondsElapsed
end #def stop
def running?()
!#watch_start_time.nil?
end #def
end #class StopWatch
end #module Utilities
def kill_time(aRepeatCount)
aRepeatCount.times do
#just killing time
end #do
end #def kill_time
elapsed_time_format_string = '%.3f'
myStopWatch = Utilities::StopWatch.new()
puts 'total time elapsed: ' + elapsed_time_format_string % myStopWatch.start() + ' seconds'
kill_time(10000000)
puts 'lap time: ' + elapsed_time_format_string % myStopWatch.lap_time_seconds() + ' seconds'
kill_time(20000000)
puts 'lap time: ' + elapsed_time_format_string % myStopWatch.lap_time_seconds() + ' seconds'
kill_time(30000000)
puts 'lap time: ' + elapsed_time_format_string % myStopWatch.lap_time_seconds() + ' seconds'
puts 'total time elapsed: ' + elapsed_time_format_string % myStopWatch.stop() + ' seconds'
Simple stopwatch script:
# pass the number of seconds as the parameter
seconds = eval(ARGV[0]).to_i
start_time = Time.now
loop do
elapsed = Time.now - start_time
print "\e[D" * 17
print "\033[K"
if elapsed > seconds
puts "Time's up!"
exit
end
print Time.at(seconds - elapsed).utc.strftime('%H:%M:%S.%3N')
sleep(0.05)
end
Run like this in your terminal (to mark a lap, just tap enter):
# 10 is the number of seconds
ruby script.rb 10
# you can even do this:
ruby script.rb "20*60" # 20 minutes
Related
ruby GTK tcp producing core dumps
i've problems with core dumps using ruby, gtk and tcp connections. my application is much larger, but here a minimized version: GTK code (is also attached): ##################################################### require 'gtk3' require 'cairo' class DummyArray def initialize #array=[ "M",2,48.83,1.95,"L",8,50.55,0.0,62.27,0.0,63.91,5.0,48.83,1.95,"M",2,0.0,22.42,"L",8,0.0,16.95,9.77,13.2,7.27,28.44,0.0,22.42,"M",2,5.39,49.61,"L",8,0.0,48.52,0.0,35.63,0.47,35.08,5.39,49.61,"M",2,0.0,80.7,"L",6,0.0,68.28,9.38,70.31,0.0,80.7,"M",2,90.23,46.56,"L",6,100.0,35.55,100.0,48.52,90.23,46.56,"M",2,100.0,16.95,"L",6,100.0,22.42,95.47,18.67,100.0,16.95,"M",2,100.0,68.28, "L",8,100.0,80.78,99.14,81.72,94.45,67.11,100.0,68.28,"M",2,50.55,100.0,"L",6,58.98,90.47,62.27,100.0,50.55,100.0,"M",2,23.44,78.67,"L",6,33.59,67.19,38.52,81.72,23.44,78.67,"M",2,40.47,15.39,"L",6,25.39,12.34,35.63,0.86,40.47,15.39,"M",2,59.61,39.77,"L",6,59.14,24.38,72.66,31.56,59.61,39.77,"M",2,45.78,36.95,"L",6,55.23,36.48,50.94,45.0,45.78,36.95, "M",2,48.98,24.38,"L",6,43.67,16.41,53.2,15.86,48.98,24.38,"M",2,22.58,10.08,"L",6,13.52,13.13,15.47,3.75,22.58,10.08,"M",2,18.28,30.47,"L",6,21.33,39.53,11.95,37.58,18.28,30.47,"M",2,25.23,40.86,"L",6,26.41,25.55,39.06,34.22,25.23,40.86,"M",2,13.67,63.13,"L",6,13.13,47.73,26.64,54.92,13.67,63.13,"M",2,17.66,68.52,"L",6,21.72,77.19,12.11,76.25,17.66,68.52,"M",2,52.34,49.06, "L",6,44.14,62.11,36.95,48.52,52.34,49.06,"M",2,52.42,79.84,"L",6,60.08,66.56,67.73,79.84,52.42,79.84,"M",2,47.42,76.25,"L",6,42.19,68.28,51.72,67.73,47.42,76.25,"M",2,79.14,31.48,"L",6,87.11,26.17,87.73,35.7,79.14,31.48,"M",2,81.64,20.08,"L",6,74.92,6.25,90.23,7.34,81.64,20.08,"M",2,67.97,10.86,"L",6,68.52,20.39,59.92,16.09,67.97,10.86,"M",2,73.59,73.36,"L",6,81.48,68.2,82.11,77.73,73.59,73.36, "M",2,63.59,49.06,"L",6,64.22,58.59,55.62,54.3,63.59,49.06,"M",2,79.53,43.83,"L",6,84.45,58.36,69.38,55.31,79.53,43.83,"M",2,90.23,95.16,"L",6,92.19,85.78,99.3,92.11,90.23,95.16,"M",2,86.17,81.48,"L",6,82.34,96.33,71.41,85.55,86.17,81.48,"M",2,22.11,97.34,"L",6,6.8,97.34,14.45,84.06,22.11,97.34,"M",2,38.2,93.05,"L",6,29.14,96.09,31.09,86.72,38.2,93.05, "Z",0 ] end def render(cr) i= 0 size= #array.size while i < size e= #array[i] case e when 'M', 'L' count= #array[i+1] j= i + 2 i= j + count while j < i x= #array[j] y= #array[j+1] if e == 'M' cr.move_to(x, y) else cr.line_to(x, y) end j += 2 end when 'Z' count= #array[i+1] j= i + 2 i= j + count cr.close_path else raise end end end end class ArtScrollCanvas < Gtk::Grid def initialize super #user_zoom= 1.0 #darea = Gtk::DrawingArea.new #darea.hexpand= true #darea.vexpand= true #darea.signal_connect('configure-event') do print "\n darea_configure_callback" update_adjustments_and_paint(0.0, 0.0) end #darea.signal_connect "draw" do |_, cr| paint(cr) end attach(#darea, 0, 0, 1, 1) update_adjustments_and_paint(0.0, 0.0) end def update_adjustments_and_paint(dx= 0.0, dy= 0.0) #darea.queue_draw_area(0, 0, #darea.allocation.width, #darea.allocation.height) end def paint(cr) cr.set_source_rgba(1, 1, 1, 1) cr.paint cr.set_source_rgba(1, 0, 0, 1) DummyArray.new.render(cr) #DummyDirect.new.render(cr) cr.fill end end class ArtApplicationWindow < Gtk::ApplicationWindow def initialize(application) super(application) signal_connect('destroy') do #Gtk.main_quit application.quit end set_title 'Art' set_size_request(600, 400) #canvas = ArtScrollCanvas.new #vbox = Gtk::Box.new(:vertical, 0) #vbox.pack_start(#canvas, :expand => true, :fill => true, :padding => 0) add(#vbox) show_all end end # ArtApplicationWindow class ArtApp < Gtk::Application def initialize super("org.gtk.exampleapp", :handles_open) signal_connect('activate') do |application| window = ArtApplicationWindow.new(application) window.present end end end begin ss = Gio::SocketService.new ss.add_inet_port(4321) ss.signal_connect("incoming") do |_, conn, _| print "\n#############################################################" print "\nconn.local_address: ", conn.local_address print "\nconn.local_address.family: ", conn.local_address.family print "\nconn.remote_address: ", conn.remote_address print "\nconn.class: ", conn.class print "\nconn.input_stream.fd: ", conn.input_stream.fd print "\nconn.input_stream.socket.fd: ", conn.input_stream.socket.fd # prevents closing the connection (at least in c code) Gtk::Loader.reference_gobject(conn) Gtk::Loader.reference_gobject(conn.input_stream) Gtk::Loader.reference_gobject(conn.input_stream.socket) Gtk::Loader.reference_gobject(conn.output_stream) Gtk::Loader.reference_gobject(conn.output_stream.socket) channel= GLib::IOChannel.new(conn.input_stream.socket.fd) channel.add_watch(GLib::IOChannel::IN) do print "\n>>> ", conn.input_stream.socket.fd len= conn.input_stream.socket.available_bytes input= conn.input_stream.read(len) print "\ninput= ", input conn.output_stream.write("OK\n") GLib::Source::CONTINUE true end true end ss.start end GLib::Timeout.add(10000) do print "\ntimer" GLib::Source::CONTINUE end app = ArtApp.new app.run ################################################# SIMPLE client: require 'socket' class Comm def initialize(socket, verbose: false) #socket= socket #sio= StringIO.new #verbose= verbose end def close #socket.close end def <<(str) #sio << str end def send str= #sio.string #socket.write(str) print "\n>>>\nsending: ", str if #verbose #sio.reopen res= #socket.readline print "\nres= \"", res, "\"" if #verbose res end end server_socket = TCPSocket.open("localhost", 4321) comm= Comm.new(server_socket, verbose: true) i= 1000000 while true i += 1 comm << i.to_s comm.send sleep(0.025) # 40 per s end in the beginning everything seems ok, but after the client is launched resizing the GTK window leads to core dumps after approx. 1000 messages (sometimes much less, but sometimes much later). Shortening the #array in DummyArray leads to less core dumps, therefore the array is that large. i've read https://ruby-gnome2.osdn.jp/hiki.cgi?tips_threads but don't know how this would apply to my program ... cheers artur
using a global array $channels= [] and adding each new channel to it channel= GLib::IOChannel.new(conn.input_stream.socket.fd) $channels << channel seems to prevent garbage collecting the channel (not well documented :-(, this answer came from the ruby-gnome2 mailing list
Why an obvious condition is not fulfilled?
I work on task about schedule and have class and .yml file where i want to retrieve data as "start" point, "end" point, "price" etc. And in my class I have method, where i want to determine if stations equal to user choice: class Train require 'yaml' def initialize(time) #time = YAML.load_file(time) end def calc(begin:, end:) ary = #time['time'] start = begin stop = end res = [] loop do tmp = ary.find { |h| h['begin'] == start } break unless tmp res << tmp start = tmp['end'] break if start == stop end end end But it always fails on condition break unless tmp For example if write instance variable a = Train.new("my_path_to yml") a.calc(begin: ':washington', end: ':tokyo') It executes nothing. Even if I refactor loop block and write "for" iterator it throw "else" condition: for i in ary if i['begin'] == 'washington' puts "good" else puts "no way" end end Here is my .yml file time: - begin: :washington end: :briston time: 6 price: 3 - begin: :briston end: :dallas time: 4 price: 2 - begin: :dallas end: :tokyo time: 3.5 price: 3 - begin: :tokyo end: :chicago time: 3.5 price: 3 - begin: :chicago end: :dellawer time: 3.5 price: 3 Thanks in advance!
Try this change, check comments in code: def calc(begin_:, end_:) # <-- don't call variables begin or end, they are reserved words ary = #time['time'] start = begin_ stop = end_ res = [] loop do tmp = ary.find { |h| h['begin'] == start } break unless tmp res << tmp start = tmp['end'] break if start == stop end res # <-- return something end Call as: train.calc(begin_: :washington, end_: :tokyo) #=> [{"begin"=>:washington, "end"=>:briston, "time"=>6, "price"=>3}, {"begin"=>:briston, "end"=>:dallas, "time"=>4, "price"=>2}, {"begin"=>:dallas, "end"=>:tokyo, "time"=>3.5, "price"=>3}] Take care not messing up strings with symbols. ary.each do |i| # for i in ary <-- pythonic! :) if i['begin'] == :washington # <-- should be a symbol to pass, not a string puts "good" else puts "no way" end end
How do I pass in code to functions?
I have this piece of code that executes a series of commands and keep retrying until it reaches MAX_RETRIES. I don't want to repeat this over and over again for different commands. Is there an elegant way of doing so? retries = 0 ex = true MAX_RETRIES = 10 while(retries <= MAX_RETRIES and ex) begin #MY CODE HERE ex = false rescue ex = true end retries = retries + 1 end Something like this? execute_with_retries do #CODE HERE end execute_with_retries do #DIFFERENT CODE HERE end
Define a function and execute the block def execute_with_retries retries = 0 ex = true max_retries = 10 while(retries <= max_retries and ex) begin yield ex = false rescue ex = true end retries = retries + 1 end end execute_with_retries { puts "hello" } execute_with_retries { puts 1/0 } I renamed one of your variable and you can read here why. It's also worth noting that something like this exists in Ruby and you can read about it here.
MAX_RETRIES = 10 def execute_with_retries(meth) retries = 0 ex = true while(retries <= MAX_RETRIES and ex) begin public_send(meth) ex = false rescue ex = true end retries = retries + 1 end retries end require 'time.h' def meth sleep(1) puts "Time.now in m = #{Time.now}" puts Time.now - #start < 5 ? "cat"/9 : "dog" end #start = Time.now #=> 2017-12-30 13:39:20 -0800 execute_with_retries(:meth) Time.now in m = 2017-12-30 13:39:21 -0800 Time.now in m = 2017-12-30 13:39:22 -0800 Time.now in m = 2017-12-30 13:39:23 -0800 Time.now in m = 2017-12-30 13:39:24 -0800 Time.now in m = 2017-12-30 13:39:25 -0800 "dog" #=> 5
resque worker error when forking [Ruby, Redis]
I'm having a difficulty with processing resque tasks which were enqueued. The whole enqueuing part goes well - I can see it in Redis and also Resque.info shows the pending tasks number incrementing as it should. If I run the perform method of the Job class explicitly - everything works fine. Once the worker come alive - all the tasks fail. This is the Job class: class TestJob #queue = :test1_queue def self.perform(str) begin f = open('/tmp/test.txt', 'a') f.write("#{Time.now.to_s} #{str} in self.perform\n") rescue Exception => e f.write("#{Time.now.to_s} #{str} in self.perform\n#{e.message}\n#{e.backtrace}\n") ensure f.close end end end The resque.rb initializer: require 'resque' require 'redis' Dir['../../jobs'].each { |file| require file } Resque.redis = $resque_redis Resque.logger.level = Logger::WARN Resque.after_fork do |_| $resque_redis.client.reconnect end Redis initializer: require 'redis' $resque_redis = Redis.new(:host => REDIS_BITMAP_HOST, :port => REDIS_PORT, :db => 0, :timeout => 30) config file to start the worker with god: require_relative './common.rb' watch_resque_process('test1', 1) God definitions: $home_dir = ENV["HOME"] $rack_env = ENV["ETL_ENV"] || "development" def create_deafult_monitoring_scheme(watch) # Restart if memory is above 150 Megabytes or CPU is above 50% for 5 consecutive intervals watch.restart_if do |restart| restart.condition(:memory_usage) do |c| c.above = 150.megabytes c.times = [3, 5] # 3 out of 5 intervals end restart.condition(:cpu_usage) do |c| c.above = 50.percent c.times = 5 end end # The :flapping condition guards against the edge case wherein god rapidly starts or restarts your application. # If this watch is started or restarted five times withing 5 minutes, then unmonitor it for 10 minutes. # After 10 minutes, monitor it again to see if it was just a temporary problem; if the process is seen to be flapping five times within two hours, then give up completely. watch.lifecycle do |on| on.condition(:flapping) do |c| c.to_state = [:start, :restart] c.times = 5 c.within = 5.minute c.transition = :unmonitored c.retry_in = 10.minute c.retry_times = 5 c.retry_within = 30.minute end end end def watch_resque_process(resque_process_name, worker_count=8) God.watch do |w| w.name = "resque_work-#{resque_process_name}" w.start = "cd #{$home_dir}/rtb-etl && COUNT=#{worker_count} QUEUE='#{resque_process_name}_queue' RACK_ENV=#{$rack_env} rake resque:workers" w.interval = 30.seconds w.log = File.join($home_dir, 'logs', 'resque', "resque_#{resque_process_name}.log") w.err_log = File.join($home_dir, 'logs', 'resque', "resque_#{resque_process_name}.log") w.env = { 'PIDFILE' => "#{$home_dir}/pids/#{w.name}.pid" } # Check if the process is still up every 5 seconds w.start_if do |start| start.condition(:process_running) do |c| c.interval = 5.seconds c.running = false end end create_deafult_monitoring_scheme(w) end end def watch_rake_task(rake_task_name, interval=30.seconds) God.watch do |w| w.name = "rake_#{rake_task_name}" # w.start = "cd #{$home_dir}/rtb-etl && RACK_ENV=#{$rack_env} bundle exec rake #{rake_task_name}" w.start = "cd #{$home_dir}/rtb-etl && RACK_ENV=#{$rack_env} rake #{rake_task_name}" w.interval = interval w.log = File.join($home_dir, 'logs', 'resque', "rake_#{rake_task_name}.log") w.err_log = File.join($home_dir, 'logs', 'resque', "rake_#{rake_task_name}.log") w.env = { 'PIDFILE' => "#{$home_dir}/pids/#{w.name}.pid" } # Check if the process is still up every 30 seconds w.start_if do |start| start.condition(:process_running) do |c| c.interval = interval c.running = false end end create_deafult_monitoring_scheme(w) end end when I run the follwoing: irb(main):004:0> Resque.enqueue(TestJob, 'foo') => true In order to check what went wrong, I run in irb the following: Resque::Failure.all(0,20).each { |job| puts "#{job["exception"]} #{job["backtrace"]}" } and get this result: [{"failed_at"=>"2015/08/26 17:35:00 UTC", "payload"=>{"class"=>"TestJob", "args"=>["foo"]}, "exception"=>"NoMethodError", "error"=>"undefined method `client' for nil:NilClass", "backtrace"=>[], "worker"=>"ip-172-31-11-211:5006:test1_queue", "queue"=>"test1_queue"}] Any ideas ?
syntax error, unexpected keyword_end, expecting '}' [closed]
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 10 years ago. I have gotten this syntax error message: /usr/src/check_in/lib/check_in.rb:105: syntax error, unexpected keyword_end, expecting '}' class CheckIn < Adhearsion::CallController def run answer #play 'welcome.wav' # "Welcome to the PSG check in application." logger.info "#{call.from.to_s} called at #{time.now.to_s}" if verify_phone(call.from) == false # If it's not a site phone logger.info "Number not recognised, routing to Ops" #play 'not_site_phone.wav' # "Number not recognized." #dial(sip:number) # Dial operations hangup else user = verify_uid # Checks the User Id end if to_check_out?(user.uid) check_out(user.uid) else update_shift(user.uid) #play 'thank_you.wav' end end def verify_uid count = 1 # Generic count variable input = ask 'enter_uid.wav', :limit => 5, :timeout => 5.seconds #takes user ID as DTMF while (count <= 3 ) # Tracks the number of attempts if User.find_by_uid(input.response) == nil # If user.find doesn't return anything logger.info "Invalid user ID. ID entered = #{input.response} Attepmt = #{count}" input = ask "please_try_again.wav", :limit => 5, :timeout => 10.seconds count += 1 # Get user to try again elsif count == 3 play "try_again_later.wav" #"Please try you again later" logger.info "Tries exceeded, played try again later." hangup else #user = User.find_by_uid(input) # Assigns the user variable to return. logger.info "User ID: #{#user.uid} is valid" return #user end end end def verify_phone(caller_id) if Sites.find_by_site_phone(caller_id) != nil return true else return false end end def update_shift (user_id) #user = User.find_by_uid(user_id) # Grabs the user object if (#user.checked_in?) # If the user is already checked in assign the relevant attributes #user.time_olc = time.now #user.num_ci += 1 #user.check_in.create_check_in(:site_id => #user.site_id, uid => #user.uid, :time => time.now) logger.info "#{#user.uid} checked in at #{#user.time_olc}" else # Otherwise set all the attributes for the shift #user.update_attributes(:checked_in? => true, :time_in => time.now, :time_olc => time.now, :num_ci => 1, :site_id => #user.site.find_by_site_phone(call.from)) #user.check_in.create_check_in(:site_id => #user.site_id, uid => #user.uid, :time => time.now) logger.info "#{#user.uid} punched in at #{#user.time_in}" end end def to_check_out?(user_id) # Method to see if the user has reached check out #user = User.find_by_uid(user_id) num_of_ci = #user.num_ci + #user.num_notifications if (num_of_ci >= #user.site.shift_len) return true else return false end end def check_out!(user_id) #user = User.find_by_uid(user_id) input = ask 'check_out?.wav', :limit => 1, :timeout => 5.seconds if (input == 1) update(#user.uid) else #user.time_out = time.now #user.time_olc = time.now #user.update_attributes(:checked_in => false) end report_for_user(uid) end def secure count = 1 play 'secure.wav' sec = 5.times.map {Random.rand(0..9) result = ask %w"#{sec[0]}, #{sec[1]}, #{sec[2]}, #{sec[3]}, #{sec[4]}", :limit => 5, :timeout => 5.seconds while (count <= 3) if (sec.join == result.response) logger.info "Check in valid" return true elsif (count < 3) result = ask 'please_try_again.wav', :limit => 5, :timeout => 5.seconds else play 'try_again_later.wav' hangup end end end def report_for_user(user_id) #user = Users.find_by_uid(user_id) report = file.open("/report/#{user_id}-#{#user.site_id}-#{date.current}",w) user_check_ins = #user.check_in.all report.write("Time, Site ID, User ID") user_check_ins.each do |check_in| report.write("#{user.check_in.time}, #{user.check_in.site_id}, #{user.checkin.uid}") check_in.destroy end end def notify foo = Users.all foo.each do |user| if user.checked_in? t1 = Time.now #sets a time place holder t2 = user.time_olc convert_time = (t1.hour * 60 * 60) + (t1.min * 60) + t1.sec convert_tolc = (t2.hour * 60 * 60) + (t2.min * 60) + t1.sec if ((convert_time - convert_tolc)/60 > 75) user.num_notification += 1 a = user.uid.to_s logger.info "#{user.uid} hasn't checked in this hour" # Adhearsion::OutboundCall.originate '+tel: Mobile' :from => ' ' do # answer # play a[0], a[1], a[2], a[3], a[4], 'has_not_checked_in.wav' # hangup # end end end end end end
In this method you have opened one curly bracket '{' but not closed it. def secure count = 1 play 'secure.wav' sec = 5.times.map {Random.rand(0..9) result = ask %w"#{sec[0]}, #{sec[1]}, #{sec[2]}, #{sec[3]}, #{sec[4]}", :limit => 5, :timeout => 5.seconds while (count <= 3) if (sec.join == result.response) logger.info "Check in valid" return true elsif (count < 3) result = ask 'please_try_again.wav', :limit => 5, :timeout => 5.seconds else play 'try_again_later.wav' hangup end end end
you are missing a closing brace in secure method at the following line sec = 5.times.map {Random.rand(0..9)