Class: Mzl::DSLProxy

Inherits:
Object
  • Object
show all
Defined in:
lib/mzl/dsl_proxy.rb

Instance Method Summary collapse

Constructor Details

#initializeDSLProxy

Returns a new instance of DSLProxy.



3
4
5
# File 'lib/mzl/dsl_proxy.rb', line 3

def initialize
  @defs = {}
end

Instance Method Details

#def(m, opts, &block) ⇒ Object

define a method that will be available on objects created with the mzl object that created this object

Raises:

  • (ArgumentError)


9
10
11
12
# File 'lib/mzl/dsl_proxy.rb', line 9

def def(m, opts, &block)
  raise ArgumentError if defs.include?(m)
  @defs[m] = [block, opts]
end

#defsObject

a list of our methods



15
16
17
# File 'lib/mzl/dsl_proxy.rb', line 15

def defs
  @defs.keys
end

#exec_for(instance, &block) ⇒ Object

execute the block against the instance with our methods available. afterwards, remove the :persist => false ones



47
48
49
50
51
52
53
54
# File 'lib/mzl/dsl_proxy.rb', line 47

def exec_for(instance, &block)
  insert_mzl(instance)
  instance.instance_exec(&block)
  extract_mzl(instance)

  # return the instance
  instance
end

#extract_mzl(instance) ⇒ Object

remove all our methods



39
40
41
42
43
# File 'lib/mzl/dsl_proxy.rb', line 39

def extract_mzl(instance)
  defs.each do |m|
    instance.singleton_class.send(:remove_method, m) unless persist?(m)
  end
end

#insert_mzl(instance, filter = {}) ⇒ Object

define our DSL methods on the instance’s metaclass



30
31
32
33
34
35
36
# File 'lib/mzl/dsl_proxy.rb', line 30

def insert_mzl(instance, filter = {})
  @defs.each do |m, ary|
    blk, opts = ary
    next unless filter.empty? || opts == filter
    instance.singleton_class.send(:define_method, m, &blk)
  end
end

#persist?(m) ⇒ Boolean

leave this def on the instance? (so it is accessible without mzl)

Returns:

  • (Boolean)


20
21
22
# File 'lib/mzl/dsl_proxy.rb', line 20

def persist?(m)
  @defs[m][1][:persist]
end

#proc_for(m) ⇒ Object

the proc for a def is the first element of the array in @defs



25
26
27
# File 'lib/mzl/dsl_proxy.rb', line 25

def proc_for(m)
  @defs[m][0]
end