lib/elevate/operation.rb in elevate-0.3.3 vs lib/elevate/operation.rb in elevate-0.4.0

- old
+ new

@@ -1,36 +1,46 @@ module Elevate + class Context + def initialize(args, &block) + metaclass = class << self; self; end + metaclass.send(:define_method, :execute, &block) + + args.each do |key, value| + instance_variable_set("@#{key}", value) + end + end + end + class ElevateOperation < NSOperation - def initWithTarget(target) + def initWithTarget(target, args:args) if init() - @target = target @coordinator = IOCoordinator.new - @dispatcher = Dispatcher.new + @target = target + @context = Context.new(args, &target) + @finished_callback = nil setCompletionBlock(lambda do - @target = nil + if @finished_callback + @finished_callback.call(@result, @exception) unless isCancelled + end - @dispatcher.invoke_finished_callback() unless isCancelled() - @dispatcher.dispose() + Dispatch::Queue.main.sync do + @target = nil + @finished_callback = nil + end end) end self end def cancel - @coordinator.cancel() + @coordinator.cancel super end - def dealloc - #puts 'dealloc!' - - super - end - def inspect details = [] details << "<canceled>" if @coordinator.cancelled? details << "@target=#{@target.class.name}" @@ -42,33 +52,39 @@ end def main log " START: #{inspect}" - @coordinator.install() + @coordinator.install begin unless @coordinator.cancelled? - @result = @target.execute + @result = @context.execute end rescue Exception => e @exception = e end - @coordinator.uninstall() + @coordinator.uninstall log "FINISH: #{inspect}" end attr_reader :exception attr_reader :result def on_started=(callback) - @dispatcher.on_started = callback + started_callback = callback + started_callback.retain + + Dispatch::Queue.main.async do + started_callback.call unless isCancelled + started_callback.release + end end def on_finished=(callback) - @dispatcher.on_finished = callback + @finished_callback = callback end end end