Skip to content

Instantly share code, notes, and snippets.

@tompng
Created April 28, 2020 13:02
Show Gist options
  • Save tompng/780c1a9ac854057583f70874a59fd255 to your computer and use it in GitHub Desktop.
Save tompng/780c1a9ac854057583f70874a59fd255 to your computer and use it in GitHub Desktop.
ruby import from
module Imports
refine(Object) do
def from(mod, &block)
imports = []
if block
RubyVM::AbstractSyntaxTree.of(block).children[2].children.each do |node|
case node.type
when :VCALL
imports << node.children[0]
when :DASGN_CURR
node.children in [name, subnode]
imports << [subnode.children[0], name]
end
end
else
imports = mod.methods false
end
Module.new do
refine(Object) do
imports.each do |name, as = name|
begin
define_method as, &mod.method(name)
rescue
const = mod.const_get(name)
define_method(as) { const }
end
end
end
end
end
end
end
main_class = self.singleton_class
Imports.module_eval do
refine(main_class) do
alias import using
end
end
require_relative './imports'
using Imports
import from(Math) { sin; cos; tan }
p cos(3.1415926535 / 3) #=> 0.5
p sin(3.1415926535 / 3) #=> 0.866
import from(Math) { cos = sin; sin = cos; pi = PI; log = log10 }
p cos(pi / 3) #=> 0.866
p sin(pi / 3) #=> 0.5
p log(100000) #=> 5
import from Math
p log2(8) #=> 3
p 4 * atan(1) #=> 3.14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment