lib/ib-ruby/connection.rb in ib-ruby-0.7.2 vs lib/ib-ruby/connection.rb in ib-ruby-0.7.3

- old
+ new

@@ -153,38 +153,32 @@ @subscribers ||= Hash.new { |hash, subs| hash[subs] = Hash.new } end ### Working with received messages Hash - # Hash of received messages, keyed by message type - def received - @received ||= Hash.new { |hash, message_type| hash[message_type] = Array.new } - end - - # Check if messages of given type were received at_least n times - def received? message_type, times=1 - received[message_type].size >= times - end - # Clear received messages Hash def clear_received *message_types if message_types.empty? received.each { |message_type, container| container.clear } else message_types.each { |message_type| received[message_type].clear } end end - # Wait for specific condition(s) - given as callable/block, or - # message type(s) - given as Symbol or [Symbol, times] pair. - # Timeout after given time or 1 second. - def wait_for *args, &block - timeout = args.find { |arg| arg.is_a? Numeric } # extract timeout from args - end_time = Time.now + (timeout || 1) # default timeout 1 sec - conditions = args.delete_if { |arg| arg.is_a? Numeric }.push(block).compact + # Hash of received messages, keyed by message type + def received + @received ||= Hash.new { |hash, message_type| hash[message_type] = Array.new } + end - sleep 0.1 until end_time < Time.now || !conditions.empty? && + # Check if messages of given type were received at_least n times + def received? message_type, times=1 + received[message_type].size >= times + end + + # Check if all given conditions are satisfied + def satisfied? *conditions + !conditions.empty? && conditions.inject(true) do |result, condition| result && if condition.is_a?(Symbol) received?(condition) elsif condition.is_a?(Array) received?(*condition) @@ -192,9 +186,26 @@ condition.call else error "Unknown wait condition #{condition}" end end + end + + # Wait for specific condition(s) - given as callable/block, or + # message type(s) - given as Symbol or [Symbol, times] pair. + # Timeout after given time or 1 second. + def wait_for *args, &block + timeout = args.find { |arg| arg.is_a? Numeric } # extract timeout from args + end_time = Time.now + (timeout || 1) # default timeout 1 sec + conditions = args.delete_if { |arg| arg.is_a? Numeric }.push(block).compact + + until end_time < Time.now || satisfied?(*conditions) + if server[:reader] + sleep 0.05 + else + process_messages 50 + end + end end ### Working with Incoming messages from IB # Start reader thread that continuously reads messages from server in background.