Module: Deferred::Accessors::InstanceMethods

Defined in:
lib/deferred/accessors.rb

Instance Method Summary collapse

Instance Method Details

#_deferred_eventsObject (protected)



152
153
154
# File 'lib/deferred/accessors.rb', line 152

def _deferred_events
  @_deferred_events ||= Hash.new { |h,k| h[k.to_s] = Deferred.new_default }
end

#_deferred_statesObject (protected)



156
157
158
# File 'lib/deferred/accessors.rb', line 156

def _deferred_states
  @_deferred_states ||= {}
end

#_reset_deferred_event(event_name, opts = {}) ⇒ Object (protected)

always returns a deferred, even one that has no callbacks



161
162
163
164
165
# File 'lib/deferred/accessors.rb', line 161

def _reset_deferred_event(event_name, opts={})
  main_accessor_name = opts[:main_accessor_name]

  _deferred_events.delete(main_accessor_name) { Deferred.new_default }
end

#deferred_state_transition(event_name, blk = nil) ⇒ Object

Note:

This method is not threadsafe!

Like deferred_event, but called from within a method to ensure that the state transition happens only once.

It’s essentially wrapping the logic of a guard and returning a callback.

Examples:

on_stop with deferred_state_transition


class Foo
  deferred_event :stop

  def stop(&event_callback)
    deferred_state_transition(:on_stop, event_callback) do
      # handle stop cases
    end
  end
end

# which is equivalent to

class Foo
  deferred_event :stop

  def stop(&blk)
    on_stop(&blk)

    return on_stop if @state_transition[:on_stop]
    @state_transition[:on_stop] = true

    # handle stop cases

    on_stop
  end
end


137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/deferred/accessors.rb', line 137

def deferred_state_transition(event_name, blk=nil)
  event_name = event_name.to_sym
  dfr = __send__(event_name)
  
  dfr.callback(&blk) if blk

  return dfr if _deferred_states[event_name]
  _deferred_states[event_name] = true

  yield

  return dfr
end