lib/ustate/server/index.rb in ustate-client-0.0.2 vs lib/ustate/server/index.rb in ustate-client-0.0.3

- old
+ new

@@ -17,10 +17,14 @@ @db = Sequel.sqlite @threads = opts[:threads] || THREADS @pool = [] + @on_state_change = [] + @on_state_once = [] + @on_state = [] + setup_db end def clear setup_db @@ -37,16 +41,45 @@ @pool.delete Thread.current end end end - def on_state_change(old, new) + def on_state_change(old = nil, new = nil, &block) + if block_given? + @on_state_change |= [block] + else + @on_state_change.each do |callback| + callback.call old, new + end + end end - def on_state(state) + def on_state_once(state = nil, &block) + if block_given? + @on_state_once |= [block] + else + @on_state_once.each do |callback| + callback.call state + end + end end + def on_state(state = nil, &block) + if block_given? + @on_state |= [block] + else + @on_state.each do |callback| + callback.call state + end + end + end + def process(s) + if s.once + on_state_once s + return on_state s + end + if current = @db[:states][host: s.host, service: s.service] # Update if current[:time] <= s.time if current[:state] != s.state on_state_change current, s