Class: FunApi::BackgroundTasks
- Inherits:
-
Object
- Object
- FunApi::BackgroundTasks
- Defined in:
- lib/funapi/background_tasks.rb
Instance Method Summary collapse
- #add_task(callable, *args, **kwargs) ⇒ Object
- #empty? ⇒ Boolean
- #execute ⇒ Object
-
#initialize(task) ⇒ BackgroundTasks
constructor
A new instance of BackgroundTasks.
- #size ⇒ Object
Constructor Details
#initialize(task) ⇒ BackgroundTasks
Returns a new instance of BackgroundTasks.
5 6 7 8 |
# File 'lib/funapi/background_tasks.rb', line 5 def initialize(task) @task = task @tasks = [] end |
Instance Method Details
#add_task(callable, *args, **kwargs) ⇒ Object
10 11 12 13 |
# File 'lib/funapi/background_tasks.rb', line 10 def add_task(callable, *args, **kwargs) @tasks << {callable: callable, args: args, kwargs: kwargs} nil end |
#empty? ⇒ Boolean
44 45 46 |
# File 'lib/funapi/background_tasks.rb', line 44 def empty? @tasks.empty? end |
#execute ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/funapi/background_tasks.rb', line 15 def execute return if @tasks.empty? @tasks.each do |task_def| callable = task_def[:callable] args = task_def[:args] kwargs = task_def[:kwargs] @task.async do if callable.respond_to?(:call) if kwargs.empty? callable.call(*args) else callable.call(*args, **kwargs) end elsif callable.is_a?(Symbol) raise ArgumentError, "Cannot call Symbol #{callable} without a context object" else raise ArgumentError, "Task must be callable or Symbol, got #{callable.class}" end rescue => e warn "Background task failed: #{e.class} - #{e.}" warn e.backtrace.first(3).join("\n") if e.backtrace end end @task.children.each(&:wait) end |
#size ⇒ Object
48 49 50 |
# File 'lib/funapi/background_tasks.rb', line 48 def size @tasks.size end |