Module: FunctionExporter
- Defined in:
- lib/function_importer.rb
Overview
add module a method to export function.
Instance Method Summary collapse
- #create_export_module(*args) ⇒ Object
-
#export(context, *args) ⇒ Object
Example: module Utils extend FunctionExporter def escape str “escaped_#str” end end.
Instance Method Details
#create_export_module(*args) ⇒ Object
36 37 38 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 |
# File 'lib/function_importer.rb', line 36 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 parent_mod.module_eval do # renate method. method_of.each do |key, val| 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
29 30 31 32 33 34 |
# File 'lib/function_importer.rb', line 29 def export context, *args parent_mod = create_export_module(*args) context.module_eval do include parent_mod end end |