Class: Module

Inherits:
Object
  • Object
show all
Defined in:
lib/lspace/core_ext.rb

Instance Method Summary collapse

Instance Method Details

#in_lspace(*methods) ⇒ Object

Preserve lspace of all blocks passed to this function.

This wraps both the &block parameter, and also any Procs and Methods that are passed into the function directly.

If you need more complicated logic (e.g. wrapping Procs that are passed to a function in a dictionary) you’re on your own.

Examples:

class << Thread
  in_lspace :new, :start, :fork
end

LSpace.new :user_id => 2 do
  Thread.new{ LSpace[:user_id] == 2 }
end


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/lspace/core_ext.rb', line 46

def in_lspace(*methods)
  methods.each do |method|
    method_without_lspace = "#{method}_without_lspace"

    # Idempotence: do nothing if the _without_lspace method already exists.
    # method_defined? matches public and protected methods; private methods need a separate check.
    next if method_defined?(method_without_lspace) || private_method_defined?(method_without_lspace)

    alias_method method_without_lspace, method

    define_method(method) do |*args, &block|
      args.map!{ |a| (Proc === a || Method === a) ? a.in_lspace : a }
      block = block.in_lspace if block
      __send__(method_without_lspace, *args, &block)
    end

    private method if private_method_defined?(method_without_lspace)
    protected method if protected_method_defined?(method_without_lspace)
  end
end

#lspace_reader(*attrs) ⇒ Object

Create getter methods for LSpace

Assumes that your LSpace keys are Symbols.

Examples:

class Job
  lspace_reader :user_id

  def user
    User.find(user_id)
  end
end

LSpace[:user_id] = 6
Job.new.user == #<User:6>


19
20
21
22
23
24
25
# File 'lib/lspace/core_ext.rb', line 19

def lspace_reader(*attrs)
  attrs.each do |attr|
    define_method(attr) do
      LSpace[attr]
    end
  end
end