Module: Nakajima::Object

Includes:
InstanceExecHelper
Defined in:
lib/nakajima/core_ext/object.rb

Defined Under Namespace

Modules: InstanceExecHelper

Instance Method Summary collapse

Instance Method Details

#instance_exec(*args, &block) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/nakajima/core_ext/object.rb', line 37

def instance_exec(*args, &block)
  begin
    old_critical, Thread.critical = Thread.critical, true
    n = 0
    n += 1 while respond_to?(mname="__instance_exec#{n}")
    InstanceExecHelper.module_eval{ define_method(mname, &block) }
  ensure
    Thread.critical = old_critical
  end
  begin
    ret = send(mname, *args)
  ensure
    InstanceExecHelper.module_eval{ remove_method(mname) } rescue nil
  end
  ret
end

#notObject



7
8
9
10
11
12
13
# File 'lib/nakajima/core_ext/object.rb', line 7

def not
  @not ||= blank_context(:receiver => self) do
    def method_missing(sym, *args, &block)
      not @receiver.send(sym, *args, &block)
    end
  end
end

#tapObject



55
56
57
58
59
60
61
62
63
64
# File 'lib/nakajima/core_ext/object.rb', line 55

def tap
  block_given? ? (yield(self); self) : begin
    blank_context(:me => self) do
      def method_missing(sym, *args, &block)
        @me.__send__(sym, *args, &block)
        @me
      end
    end
  end
end

#try(method_id, *args, &block) ⇒ Object



3
4
5
# File 'lib/nakajima/core_ext/object.rb', line 3

def try(method_id, *args, &block)
  respond_to?(method_id) ? send(method_id, *args, &block) : nil
end

#with(hash) ⇒ Object

Like JavaScript, but in Ruby…



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/nakajima/core_ext/object.rb', line 16

def with(hash)
  hash.each do |key, value|
    meta_def(key) { hash[key] }
    meta_def("#{key}=") { |v| hash[key] = v }
  end

  return unless block_given?

  result = yield

  hash.each do |key, value|
    meta_eval { remove_method(key) }
    meta_eval { remove_method("#{key}=") }
  end

  result
end