Class: Module

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

Instance Method Summary collapse

Instance Method Details

#delegate_key(*methods, to: nil, prefix: nil, private: nil) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/delegate_key.rb', line 2

def delegate_key(*methods, to: nil, prefix: nil, private: nil)
  unless to
    raise ArgumentError, "Delegation needs a target. Supply a keyword argument 'to' (e.g. delegate_key :key, to: :some_hash)."
  end

  if prefix == true && /^[^a-z_]/.match?(to)
    raise ArgumentError, "Can only automatically set the delegation prefix when delegating to a method."
  end

  method_prefix = prefix ? "#{prefix == true ? to : prefix}_" : ""

  location = caller_locations(1, 1).first
  file, line = location.path, location.lineno

  method_def = []
  method_names = methods.each do |method|
    method_def <<
      "def #{method_prefix}#{method}" <<
      "  #{to}.public_send(:[], #{method.inspect})" <<
      "end"
  end

  module_eval(method_def.join(";"), file, line)
  private(*method_names) if private
  method_names
end