Module: Deferred::Accessors::ClassMethods

Defined in:
lib/deferred/accessors.rb

Instance Method Summary collapse

Instance Method Details

#deferred_event(*event_names) ⇒ Object

creates a DefaultDeferred and attr_reader on the given class the method created allows for a block to be given, which will be added to the callback chain.

Also defines a “reset_blah_event” that lets you create a new deferred for that event. The reset_event method will return the deferred being replaced.

Examples:

usage


class Foo
  include Deferred::Accessors

  deferred_event :stop
end

f = Foo.new

# you can use on_stop as Deferred object

f.on_stop.callback do
  puts "called back"
end

f.on_stop.errback do
  puts "erred back"
end

# or you can just hand a block that will be added to the callback
# chain

f.on_stop do
  puts "this is the callback chain"
end

reset method


class Foo
  include Deferred::Accessors

  deferred_event :stop

  # this method fires the stop callbacks and re-arms them
  def restart
    dfr = reset_stop_event

    # do stuff that requires stop
    dfr.succeed
  end
end

Parameters:

  • opts (Hash)

    a customizable set of options



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/deferred/accessors.rb', line 65

def deferred_event(*event_names)
  opts = event_names.extract_options!
  opts = {:before => false, :after => false}.merge(opts)

  if opts[:prefix] != false
    opts[:prefix] ||= 'on'
  end

  event_names.each do |event_name|
    event_name = event_name.to_s

    main_accessor_name = (opts[:prefix] == false) ? event_name : "#{opts[:prefix]}_#{event_name}"

    define_method(:"reset_#{event_name}_event") do
      _reset_deferred_event(event_name, opts.merge(:main_accessor_name => main_accessor_name))
    end

    create_deferred_event_reader(main_accessor_name)
  end
end