Sha256: 4bcaad172c7c4223ca8fd632f3337f61044836bbbe574e7bee56ec4c0fca11fa

Contents?: true

Size: 1.08 KB

Versions: 29

Compression:

Stored size: 1.08 KB

Contents

module Artoo
  # Class that handles events
  module Events

    # Subscribe to an event from a device
    # @param [Device] device
    # @param [Hash]   events
    def on(device, events={})
      events.each do |k, v|
        subscribe("#{safe_name}_#{device.name}_#{k}", create_proxy_method(k, v))
      end
    end

    # Create an anonymous subscription method so we can wrap the
    # subscription method fire into a valid method regardless
    # of where it is defined
    # @param [String] base_name
    # @param [String] v
    def create_proxy_method(base_name, v)
      proxy_method_name(base_name).tap do |name|
        self.class.send :define_method, name do |*args|
          case v
          when Symbol
            self.send v.to_sym, *args
          when Proc
            v.call(*args)
          end
        end
      end
    end

    # A simple loop to create a 'fake' anonymous method
    # @return [Method] created method
    def proxy_method_name(base_name)
      begin
        meth = "#{base_name}_#{Random.rand(999)}"
      end while respond_to?(meth)
      meth
    end
  end
end

Version data entries

29 entries across 29 versions & 1 rubygems

Version Path
artoo-1.8.2 lib/artoo/events.rb
artoo-1.8.1 lib/artoo/events.rb
artoo-1.8.0 lib/artoo/events.rb
artoo-1.6.7 lib/artoo/events.rb
artoo-1.6.6 lib/artoo/events.rb
artoo-1.6.5 lib/artoo/events.rb
artoo-1.6.4 lib/artoo/events.rb
artoo-1.6.3 lib/artoo/events.rb
artoo-1.6.2 lib/artoo/events.rb
artoo-1.6.1 lib/artoo/events.rb
artoo-1.6.0 lib/artoo/events.rb
artoo-1.5.0 lib/artoo/events.rb
artoo-1.4.1 lib/artoo/events.rb
artoo-1.4.0 lib/artoo/events.rb
artoo-1.3.0 lib/artoo/events.rb
artoo-1.2.2 lib/artoo/events.rb
artoo-1.2.1 lib/artoo/events.rb
artoo-1.2.0 lib/artoo/events.rb
artoo-1.1.1 lib/artoo/events.rb
artoo-1.1.0 lib/artoo/events.rb