I'd like to provide some refinements to a DSL. I'm able to get refinements working with this example:
module ArrayExtras
refine Array do
def speak
puts 'array!'
end
end
end
module MyUniverse
using ArrayExtras
class Thing
def initialize
[1].speak
end
end
end
MyUniverse::Thing.new
This prints out "array!" just fine. But once I introduce instance_eval, the method can't be found:
module MyUniverse
using ArrayExtras
class DSL
def initialize(&block)
instance_eval(&block)
end
end
end
MyUniverse::DSL.new do
[1].speak
end
I get a undefined methodspeak' for [1]:Array (NoMethodError)`
Is there a way to get refinements working within an instance_eval?
Refinements are lexically scoped. You are activating the Refinement in the wrong lexical context. You need to activate it where you are calling the refined method:
module ArrayExtras
refine Array do
def speak
puts 'array!'
end
end
end
module MyUniverse
class DSL
def initialize(&block)
instance_eval(&block)
end
end
end
using ArrayExtras
MyUniverse::DSL.new do
[1].speak
end
# array!
In some cases you can achieve it by using ArrayExtras on the binding.
module MyUniverse
using ArrayExtras
class DSL
def initialize(&block)
block.binding.eval("using ArrayExtras")
instance_eval(&block)
end
end
end
MyUniverse::DSL.new do
[1].speak
end
This will however only work if you are not using your class in an instance, it only works if the binding is a module or class context, otherwise the eval will fail because main.using is permitted only at toplevel .
If you want to refine the ruby core BaseObject, you need to modify it as below.
module ArrayExtras
refine ::Array do
def speak
puts 'array!'
end
end
end
It will be found in top level class.
Related
I have a module I'd like to be able to wrap every method in a class, whether it be an instance method or a class method, but am having a bit of trouble trying to get it to work in both circumstances. Below is what I have right now, it works for wrapping instance methods but calling class methods doesn't seem to work. I assume the module proxy isn't installed correctly for overriding class methods, but I'm not sure what to do to fix that.
I'm limited to ruby 2.7, btw.
module Wrapper
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
module Proxy
end
def wrap_method(name)
puts "wrapping #{name}"
Proxy.define_method(name) do |*args|
puts "in wrap_method, about to call #{name}"
super *args
end
end
def wrap_methods
# wrap any methods that were defined before this was called
self.instance_methods(false).each {|name| wrap_method(name) }
self.singleton_methods(false).each {|name| wrap_method(name) }
# wrap any methods that are defined after this is called
self.class.define_method(:singleton_method_added) do |name|
if respond_to?(:wrap_method)
wrap_method(name)
end
end
self.class.define_method(:method_added) do |name|
if respond_to?(:wrap_method)
wrap_method(name)
end
end
self.prepend(Proxy)
end
end
end
module Top
module Second
class Main
include Wrapper
wrap_methods
def self.first_class_method
puts "in self.first_class_method"
end
def self.second_class_method
puts "in self.second_class_method"
end
def some_instance_method
puts "in some_instance_method"
end
end
end
end
Top::Second::Main.first_class_method
Top::Second::Main.second_class_method
Top::Second::Main.new.some_instance_method
Output:
wrapping first_class_method
wrapping second_class_method
wrapping some_instance_method
in self.first_class_method
in self.second_class_method
in wrap_method, about to call some_instance_method
in some_instance_method
You prepend Proxy to the class itself, and this modifies the method resolution for instances of the class, but not for the class itself.
To achieve the second, you have to
self.singleton_class.prepend(Proxy)
in addition.
In Rails we can define a class like:
class Test < ActiveRecord::Base
before_initialize :method
end
and when calling Test.new, method() will be called on the instance. I'm trying to learn more about Ruby and class methods like this, but I'm having trouble trying to implement this in plain Ruby.
Here's what I have so far:
class LameAR
def self.before_initialize(*args, &block)
# somehow store the symbols or block to be called on init
end
def new(*args)
## Call methods/blocks here
super(*args)
end
end
class Tester < LameAR
before_initialize :do_stuff
def do_stuff
puts "DOING STUFF!!"
end
end
I'm trying to figure out where to store the blocks in self.before_initialize. I originally tried an instance variable like #before_init_methods, but that instance variable wouldn't exist in memory at that point, so I couldn't store or retrieve from it. I'm not sure how/where could I store these blocks/procs/symbols during the class definition, to later be called inside of new.
How could I implement this? (Either having before_initialize take a block/proc/list of symbols, I don't mind at this point, just trying to understand the concept)
For a comprehensive description, you can always check the Rails source; it is itself implemented in 'plain Ruby', after all. (But it handles lots of edge cases, so it's not great for getting a quick overview.)
The quick version is:
module MyCallbacks
def self.included(klass)
klass.extend(ClassMethods) # we don't have ActiveSupport::Concern either
end
module ClassMethods
def initialize_callbacks
#callbacks ||= []
end
def before_initialize(&block)
initialize_callbacks << block
end
end
def initialize(*)
self.class.initialize_callbacks.each do |callback|
instance_eval(&callback)
end
super
end
end
class Tester
include MyCallbacks
before_initialize { puts "hello world" }
end
Tester.new
Left to the reader:
arguments
calling methods by name
inheritance
callbacks aborting a call and supplying the return value
"around" callbacks that wrap the original invocation
conditional callbacks (:if / :unless)
subclasses selectively overriding/skipping callbacks
inserting new callbacks elsewhere in the sequence
... but eliding all of those is what [hopefully] makes this implementation more approachable.
One way would be by overriding Class#new:
class LameAR
def self.before_initialize(*symbols_or_callables, &block)
#before_init_methods ||= []
#before_init_methods.concat(symbols_or_callables)
#before_init_methods << block if block
nil
end
def self.new(*args, &block)
obj = allocate
#before_init_methods.each do |symbol_or_callable|
if symbol_or_callable.is_a?(Symbol)
obj.public_send(symbol_or_callable)
else
symbol_or_callable.(obj)
end
end
obj.__send__(:initialize, *args, &block)
end
end
class Tester < LameAR
before_initialize :do_stuff
def do_stuff
puts "DOING STUFF!!"
end
end
I have to wrap some behavior around an external gem in a elegant and isolated manner. Given the abstraction below, everything runs smoothly, but 'bar' is never printed.
Could someone tell me why?
My code:
module RefineGem
refine GemMainModule::GemClass do
def self.foo
p 'bar'
super
end
end
end
module Test
using RefineGem
def test
GemMainModule::GemClass.foo
end
end
class Testing
include Test
end
Testing.new.test
Gem code:
module GemMainModule
class Base
include GemMainModule::Fooable
end
class GemClass < Base
end
end
module GemMainModule
module Fooable
extend ActiveSupport::Concern
class_methods do
def foo
p 'zoo'
end
end
end
end
I doubt refinements work for class methods. You might refine the singleton_class though:
module RefineGem
refine GemMainModule::GemClass.singleton_class do
def foo
p 'bar'
super
end
end
end
I personally prefer to use Module#prepend to achieve the same functionality:
GemMainModule::GemClass.singleton_class.prepend(Module.new do
def foo
p 'bar'
super
end
end)
I'm playing with ruby's metaprogramming features, and I'm finding it a bit hairy. I'm trying to wrap a method call using a module. Currently, I'm doing this:
module Bar
module ClassMethods
def wrap(method)
class_eval do
old_method = "wrapped_#{method}".to_sym
unless respond_to? old_method
alias_method old_method, method
define_method method do |*args|
send old_method, *args
end
end
end
end
end
def self.included(base)
base.extend ClassMethods
end
end
class Foo
include Bar
def bar(arg = 'foo')
puts arg
end
wrap :bar
end
Three questions:
Is there any way to do this without renaming the method, so as to allow the use of super? Or something cleaner/shorter?
Is there a clean way to set the default values?
Is there a means to move the wrap :bar call further up?
1) Cleaner/shorter
module ClassMethods
def wrap(method)
old = "_#{method}".to_sym
alias_method old, method
define_method method do |*args|
send(old, *args)
end
end
end
class Foo
extend ClassMethods
def bar(arg = 'foo')
puts arg
end
wrap :bar
end
As far as I know there is no way to achieve this without renaming. You could try to call super inside the define_method block. But first of all, a call to super from within a define_method will only succeed if you specify arguments explicitly, otherwise you receive an error. But even if you call e.g. super(*args), self in that context would be an instance of Foo. So a call to bar would go to the super classes of Foo, not be found and ultimately result in an error.
2) Yes, like so
define_method method do |def_val='foo', *rest|
send(old, def_val, *rest)
end
However, in Ruby 1.8 it is not possible to use a block in define_method, but this has been fixed for 1.9. If you are using 1.9, you could also use this
define_method method do |def_val='foo', *rest, &block|
send(old, def_val, *rest, &block)
end
3) No, unfortunately. alias_method requires the existence of the methods that it takes as input. As Ruby methods come into existence as they are parsed, the wrap call must be placed after the definition of bar otherwise alias_method would raise an exception.
I have a Mix-in that reflects on the receiver class to generate some code. This means that I need to execute the class method at the end of the class definition, like in this trivially dumbed down example:
module PrintMethods
module ClassMethods
def print_methods
puts instance_methods
end
end
def self.included(receiver)
receiver.extend ClassMethods
end
end
class Tester
include PrintMethods
def method_that_needs_to_print
end
print_methods
end
I'd like to have the mixin do this for me automatically, but I can't come up with a way. My first thought was to add receiver.print_methods to self.included in the mixin, but that won't work because the method that I want it to reflect on has not been declared yet. I could call include PrintMethods at the end of the class, but that feels like bad form.
Are there any tricks to make this happen so I don't need to call print_methods at the end of the class definition?
First of all, there's no end of class definition. Remember that in Ruby you can reopen the Tester class method after you have 'initialized' it, so the interpreter can't know where the class 'ends'.
The solution I can come up with is to make the class via some helper method, like
module PrintMethods
module ClassMethods
def print_methods
puts instance_methods
end
end
def self.included(receiver)
receiver.extend ClassMethods
end
end
class Object
def create_class_and_print(&block)
klass = Class.new(&block)
klass.send :include, PrintMethods
klass.print_methods
klass
end
end
Tester = create_class_and_print do
def method_that_needs_to_print
end
end
But certainly having to define classes this way makes my eyes hurt.