aris
July 16, 2012, 5:36pm
1
Is it possible to do something like this with Ruby?
#!/usr/bin/env ruby
class Scope
def hello_world
puts “Hello World”
end
end
scope = Scope.new
transaction = class << scope; self; end;
Without making Scope#hello_world a class method, can we make this work
somehow?
eval “hello_world”, transaction.send(:binding)
The idea would be to provide the ability to write something along the
lines
of transaction.send(:include, MyModule) without affecting the original
instance of scope, while still providing access to all methods.
Kind regards,
Samuel
I hate to answer my own question, but after some more experimentation I
found that this works pretty well:
#!/usr/bin/env ruby
class Transaction
def scope(helpers)
helpers.class_eval do
Proc.new {}
end
end
end
module Helpers
def self.hello_world
puts “Hello World”
end
end
transaction = Transaction.new
eval “hello_world”, transaction.scope(Helpers).binding
I hope this may be useful to others.
Kind regards,
Samuel
Clearly I shouldn’t be coding at 4am. The above example doesn’t actually
work correctly =) I’m going to shut up and go to bed now.