Class: Hark::AdHoc

Inherits:
Object
  • Object
show all
Defined in:
lib/hark/ad_hoc.rb

Overview

AdHoc is a tiny class to facilitate creating an ad-hoc object that from either a hash or proc.

Eg. from a hash:

handler = AdHoc.new(success: (o)-> { o.great_success }, failure: (o)-> { o.failed } )

Eg. from a ‘response’ style block:

handler = AdHoc.new do |on|
  on.success {|o| o.great_success }
  on.failure {|o| o.failed }
end

Eg. adding methods after creation

obj = AdHoc.new
obj.add_method!(:foo) { "bar" }

All blocks keep their original binding. This makes AdHoc suitable for creating ad-hoc responses from controller type objects.

Defined Under Namespace

Classes: AddMethodsFromProc

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.new(hash = {}, &proc) ⇒ Object



24
25
26
27
28
29
# File 'lib/hark/ad_hoc.rb', line 24

def self.new hash = {}, &proc
  super().tap do |ad_hoc|
    AddMethodsFromProc.new(proc, ad_hoc) if block_given?
    hash.each {|method, body| ad_hoc.add_method!(method, &body) }
  end
end

Instance Method Details

#add_method!(method, &body) ⇒ Object



31
32
33
# File 'lib/hark/ad_hoc.rb', line 31

def add_method!(method, &body)
  singleton_class.send(:define_method, method) {|*args, &block| body.call(*args, &block) }
end