accessing instance methods from class method proc - ruby

I am trying to call a proc on a class but access instance methods from it with an inherited class. I think some mock code will make more sense :)
class Bar
def self.foo &block
#foo ||= block
end
def foo; self.class.foo.call(); end
def bar; 'bar'; end
end
class Foo < Bar
foo do
bar
end
end
Foo.new.foo
# NameError: undefined local variable or method `bar' for Foo:Class
I want to be able to access the bar instance method on the Bar class. The reason for calling the foo class method with a block from the inherited class is part of the DSL requirement, but any suggestions for a better design would be appreciated.

Blocks are lexically scoped, including the value of self. At the point where the block is defined, self is Bar and Bar doesn't respond to bar. You need to evaluate the block in the context of the object (in this case an instance of Bar and not Bar itself) whose methods you want to call. That's what instance_eval does:
class Bar
def self.foo(&block) #foo ||= block end
def foo; instance_eval(&self.class.foo) end
def bar; 'bar' end
end
class Foo < Bar; foo do bar end end
Foo.new.foo
# => 'bar'
Note that all the usual disclaimers about instance_eval apply: since you change the value of self methods and instance variables that the block author may expect to be available won't be.

Related

How to call the methods of a delegator from the wrapped object in Ruby

Let's say I have this class and delegator
class MyObject
def foo
"foo #{bar}"
end
def bar
"bar"
end
end
class MyDelegator < SimpleDelegator
def bar
"decorated bar"
end
end
MyDelegator.new(MyObject.new).foo # => "foo bar"
This obviously happens because of the method resolution chain. #foo is not found on the MyDelegator class, therefore it is delegated to the MyObject class. When MyObject#foo is called, the method in turn calls MyObject#bar.
I can have MyDelegator#foo return "foo decorated bar" this way:
class MyObject
def foo
"foo #{bar}"
end
def bar
"bar"
end
end
class MyDelegator < SimpleDelegator
module MyMethods
def bar
"decorated bar"
end
end
def initialize(object)
super
object.singleton_class.include(object)
end
end
MyDelegator.new(MyObject.new).foo # => "foo decorated bar"
I could also have defined methods on the eigenclass of the MyObject instance using define_method or instance_eval for example. My question is the following:
Is there a way I can achieve the same thing without changing the eigenclass of the wrapped object and without cloning it while keeping the wrapped object untouched for other consumers of the object downstream?

Inheritance on different namespace

I have self-writed gem
module GemNamespace
class Foo; end
class Bar
def foo
#foo ||= Foo.new
end
end
end
Also I have application
module ApplicationNamespace
class Foo < GemNamespace::Foo; end
class Bar < GemNamespace::Bar; end
end
When I call foo method at my application it returned me instanceof GemNamespace object:
bar = ApplicationNamespace::Bar.new
puts bar.foo
=> #<GemNamespace::Foo:0x007f849d8169f0>
But I want get object of ApplicationNamespace how I can do this without redefine foo method
Your Problem is not, that you have several Namespaces, but that GemNamespace::Bar is tightly coupled to GemNamespace::Foo.
You could use something like this:
class Bar
def initialize(klass)
#klass = klass
end
def foo
#foo ||= #klass.new
end
end
So instead of only ever using GemNamespace::Foo within Bar, you could pass any class.
Your current version of the foo method will allways refer to GemNamespace::Foo because its context is set at definition (not at execution). Instead you could get the module of the current executing class dynamically. I don't think there is a build-in method that does this so you have to get it manually:
def foo
#foo ||= self.class.name.split("::")[0..-2].inject(Kernel) { |s, c| s.const_get c }.const_get("Foo").new
end
This will work for any number of nested modules.

Is it possible to define class methods within `class_eval`?

I know it's possible to define instance methods using class_eval. Is it possible to define class methods within the context of class_eval?
Yes, it is possible:
class Foo
end
Foo.class_eval do
def self.bar
puts "I'm a class method defined using class_eval and self"
end
def baz
puts "I'm an instance method defined using class_eval without self"
end
end
Foo.bar # => "I'm a class method defined using class_eval and self"
foo = Foo.new
foo.baz # => "I'm an instance method defined using class_eval without self"
As far as I can tell, this is because within class_eval, self is the Foo class, and doing def Foo.bar would create a class method.
Foo.class_eval do
...
end
is identical to:
class Foo
...
end
We need Module#class_eval to operate on a variable that holds the name of a class. For example, if:
klass = Foo
you can write:
klass.class_eval do
...
end
whereas the keyword class demands a constant.
Here class_eval does two things:
it changes self to the value of klass (Foo); and then it
"opens" the value of klass (Foo) in the same way the keyword class does.

Ruby - accessing instance methods / variables from anonymous class

I have following Ruby code:
class Baz
def foo()
qux = Class.new() {
def call()
bar()
end
}.new()
qux.call()
end
def bar()
puts "bar"
end
end
b = Baz.new()
b.foo()
How can I access method bar from the anonymous class, that means from qux.call? Is it possible?
I'm keeping getting this message:
classes-test.rb:5:in `call': undefined method `bar' for #<#<Class:0x00000002d9c248>:0x00000002d9c1a8> (NoMethodError)
I'm new to Ruby, so any advice or even deeper explanation of the problem will be appreciated. Thanks in advance.
Since .bar is an instance method of Baz, you need to have an instance of Baz available in your context to call .bar. You can do that by passing the instance object to the class on initialization, so you can call its .bar method on it.
This works:
class Baz
def foo
qux = Class.new do
def initialize(a)
#a = a
end
def call
#a.bar
end
end.new(self)
qux.call
end
def bar
puts "bar"
end
end
b = Baz.new
b.foo
=> 'bar'
If you need to pass a class to Class.new() as you mention in the comments, you can override the initializer method like this (please note that you may have to consider the arguments that your Closure class initialize needs for super:
qux = Class.new(Fiddle::Closure) do
def initialize(baz)
#baz = baz
super
end
def call
#baz.bar
end
end.new(self)
On a side note, you don't need all those (), it's Ruby style to omit them if not needed.

Remove/undef a class method

You can dynamically define a class method for a class like so:
class Foo
end
bar = %q{def bar() "bar!" end}
Foo.instance_eval(bar)
But how do you do the opposite: remove/undefine a class method? I suspect Module's remove_method and undef_method methods might be able to be used for this purpose, but all of the examples I've seen after Googling for hours have been for removing/undefining instance methods, not class methods. Or perhaps there's a syntax you can pass to instance_eval to do this as well.
Thanks in advance.
class Foo
def self.bar
puts "bar"
end
end
Foo.bar # => bar
class <<Foo
undef_method :bar
end
# or
class Foo
singleton_class.undef_method :bar
end
Foo.bar # => undefined method `bar' for Foo:Class (NoMethodError)
When you define a class method like Foo.bar, Ruby puts it Foo's singleton class. Ruby can't put it in Foo, because then it would be an instance method. Ruby creates Foo's singleton class, sets the superclass of the singleton class to Foo's superclass, and then sets Foo's superclass to the singleton class:
Foo -------------> Foo(singleton class) -------------> Object
super def bar super
There are a few ways to access the singleton class:
class <<Foo,
Foo.singleton_class,
class Foo; class << self which is commonly use to define class methods.
Note that we used undef_method, we could have used remove_method. The former prevents any call to the method, and the latter only removes the current method, having a fallback to the super method if existing. See Module#undef_method for more information.
This also works for me (not sure if there are differences between undef and remove_method):
class Foo
end
Foo.instance_eval do
def color
"green"
end
end
Foo.color # => "green"
Foo.instance_eval { undef :color }
Foo.color # => NoMethodError: undefined method `color' for Foo:Class
You can remove a method in two easy ways. The drastic
Module#undef_method( )
removes all methods, including the inherited ones. The kinder
Module#remove_method( )
removes the method from the receiver, but it
leaves inherited methods alone.
See below 2 simple example -
Example 1 using undef_method
class A
def x
puts "x from A class"
end
end
class B < A
def x
puts "x from B Class"
end
undef_method :x
end
obj = B.new
obj.x
result -
main.rb:15:in
': undefined methodx' for # (NoMethodError)
Example 2 using remove_method
class A
def x
puts "x from A class"
end
end
class B < A
def x
puts "x from B Class"
end
remove_method :x
end
obj = B.new
obj.x
Result -
$ruby main.rb
x from A class
I guess I can't comment on Adrian's answer because I don't have enough cred, but his answer helped me.
What I found: undef seems to completely remove the method from existence, while remove_method removes it from that class, but it will still be defined on superclasses or other modules that have been extened on this class, etc.
If you would like to remove method with name what calculate dinamically, you should use eigenclasses like:
class Foo
def self.bar
puts "bar"
end
end
name_of_method_to_remove = :bar
eigenclass = class << Foo; self; end
eigenclass.class_eval do
remove_method name_of_method_to_remove
end
this way is better than others answers, becouse here i used class_eval with block. As you now block see current namespace, so you could use your variables to remove methods dinamically
Object.send(:remove_const, :Foo)

Resources