Class: OnEvent

Inherits:
Object
  • Object
show all
Defined in:
lib/on_event.rb,
lib/on_event/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Constructor Details

#initialize(*events) {|_self| ... } ⇒ OnEvent

Returns a new instance of OnEvent.

Yields:

  • (_self)

Yield Parameters:

  • _self (OnEvent)

    the object that the method was called on



5
6
7
8
# File 'lib/on_event.rb', line 5

def initialize(*events)
  establish_events(*events)
  yield self if block_given?
end

Instance Method Details

#establish_events(*events) ⇒ Object Also known as: establish_event

This defines an #event_name and #on_event_name method for each given event. #on_event_name takes a block stored as a callback, which is passed the args from corresponding calls to #event_name

# Regular Style:
on_event = OnEvent.new(:success, :failure)
on_event.on_success { |a| a << "A success" }
on_event.on_failure { |a| a << "A failure" }

# Block Style:
on_event = OnEvent.new(:foo, :bar) do |oe|
  oe.on_foo { |a| a << "foo" }
  oe.on_bar { |a| a << "bar" }
end

a = []
on_event.foo(a)
a # => ["foo",]
on_event.bar(a)
a # => ["foo", "bar"]


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/on_event.rb', line 33

def establish_events(*events)
  (class << self; self; end).instance_eval do
    Array(events).each do |event_name|
      define_method "on_#{event_name}" do |&block|
        event_blocks[event_name.to_sym] << block
      end

      define_method event_name do |*args|
        event_blocks[event_name.to_sym].each do |block|
          with_rescue { block.call *args }
        end
        true
      end
    end
  end
end

#loggerObject



51
52
53
# File 'lib/on_event.rb', line 51

def logger
  @logger ||= Logger.new(STDERR)
end