Module: FunctionExporter

Defined in:
lib/function_importer.rb

Overview

add module a method to export function.

Defined Under Namespace

Classes: NameError

Instance Method Summary collapse

Instance Method Details

#create_export_module(*args) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/function_importer.rb', line 39

def create_export_module *args
  parent_mod = self.dup

  method_of = {};
  case args.first
  when Hash
    args.first.each do |key, val|
      method_of[key.to_s] = val
    end
  else
    args.each do |i| 
      method_of[i.to_s] = true
    end
  end

  no_need_methods = []
  parent_mod.instance_methods.each do |meth|
    unless method_of[meth.to_s]
      no_need_methods.push meth
    end
  end

  orig_mod = self
  parent_mod.module_eval do
    # renate method.
    method_of.each do |key, val|
      begin
        raise NameError, "no such method #{key} exist in #{orig_mod}" unless instance_method(key)
      rescue ::NameError => e
        raise NameError, "no such method #{key} exist in #{orig_mod}"
      end
      next if val.kind_of? TrueClass
      alias_method val, key
      undef_method key
    end
    no_need_methods.each do |meth|
      undef_method meth
    end
  end

  parent_mod
end

#export(context, *args) ⇒ Object

Example:

module Utils
  extend FunctionExporter

  def escape str
    "escaped_#{str}"
  end
end

module Foo
  Utils.export self, :escape

  def run
    p(escape('str')) #=> "escaped_str"
  end
end

# you can rename method when argument is Hash.
module Bar
  Utils.export self, :escape => :my_escape

  def run
    p(my_escape('str')) #=> "escaped_str"
  end
end


32
33
34
35
36
37
# File 'lib/function_importer.rb', line 32

def export context, *args
  parent_mod = create_export_module(*args)
  context.module_eval do
    include parent_mod
  end
end