Generic methods/Default methods in Ruby, when some method is not defined - ruby

I want to do something but I'm not sure if it is possible. I want to use "generic methods" or "default methods" in case when some method is called but is not defined. This is a simple example so you can understand my point:
This is the class:
class XYZ
def a
#...
end
def b
#...
end
end
The instance of the class XYZ:
n = XYZ.new
n.a
n.b
n.c
As you can see, I'm calling the method "c" which is not defined and it will throw an error. Can I do something in the class XYZ so when someone calls a method not defined get the name of the method and do something, in base of the name of the method? And, is this possible in another languages (not making a compiler)? If this is possible, how is it called (theory speaking)?

Use method_missing:
class XYZ
def a; end
def b; end
def method_missing(name, *args)
"Called #{name} with args: #{args}"
end
end
XYZ.new.c #=> "Called c"
You should also define respond_to_missing? to get respond_to? to work nicer in 1.9.2+. You should read more about respond_to?/respond_to_missing? when using method_missing.
This, by the way, would be considered to be metaprogramming. This isn't typically possible in compiled languages because of the way they call functions.

its called method_missing.
When you call a method that is not defined on object, ruby redirects the call to method_missing method which raises the error for you.
you can do this:
class XYZ
def method_missing(method, *args, &blck)
puts "called #{method} with arguments #{args.join(',')}"
end
end
now instead of error you will get output to your console.

Related

Make methods dynamic in ruby

Define a class as follows. I want to call one_method dynamically. By default, wow.one_method calls the first one_method. If I want to change the behavior of the method, just call redefine.
I can implement the method as a function type property, but that is not what I want.
If I use the following code directly, it would report errors. Could you modify it slightly.
class Wow
def one_method
puts "hello Ruby"
end
def redefine(what="none")
define_method :one_method do
puts what
end
end
end
wow = Wow.new
wow.redefine("Whatever I want.")
You can achieve that via class_eval or instance_eval:
class Wow
def one_method
puts "hello Ruby"
end
def redefine(what="none")
self.class.class_eval do
define_method :one_method do
puts what
end
end
end
end
wow = Wow.new
wow.one_method #=> hello Ruby
wow.redefine("Whatever I want.")
wow.one_method #=> Whatever I want.
Reason is that define_method defines instance method on the receiver and is a class's instance method so you'll have to call it on the eigen class of the object that you want to redefine a method on.
I would recommend achieving your goal in a more canonical way, just redefine the method on the instance itself:
class Wow
def one
:one
end
end
w = Wow.new
w.one
#=> :one
def w.one
:two
end
w.one
#=> :two
Drawbacks are:
your methods lookup table caches will be dropped
the code is becoming more obscure and hard to debug
Alternatives:
I don't know your real problem, but for your particular question it is better to parameterize your one_method method just to receive an argument for puts. Also, you can pass a block, so you will receive more grained control over the behavior.

How to compose modules containing method_missing in ruby

I have a couple of modules that extend method missing:
module SaysHello
def respond_to?(method)
super.respond_to?(method) || !!(method.to_s =~ /^hello/)
end
def method_missing(method, *args, &block)
if (method.to_s =~ /^hello/)
puts "Hello, #{method}"
else
super.method_missing(method, *args, &block)
end
end
end
module SaysGoodbye
def respond_to?(method)
super.respond_to?(method) || !!(method.to_s =~ /^goodbye/)
end
def method_missing(method, *args, &block)
if (method.to_s =~ /^goodbye/)
puts "Goodbye, #{method}"
else
super.method_missing(method, *args, &block)
end
end
end
class ObjectA
include SaysHello
end
class ObjectB
include SaysGoodbye
end
This all works well, eg ObjectA.new.hello_there outputs "Hello, hello_there". Likewise, ObjectB.new.goodbye_xxx outputs "Goodbye, xxx". respond_to? also works, eg ObjectA.new.respond_to? :hello_there return true.
However, this doesn't work very well when you want to use both SaysHello and SaysGoodbye:
class ObjectC
include SaysHello
include SaysGoodbye
end
While ObjectC.new.goodbye_aaa works correctly, ObjectC.new.hello_a acts strange:
> ObjectC.new.hello_aaa
Hello, hello_aaa
NoMethodError: private method `method_missing' called for nil:NilClass
from test.rb:22:in `method_missing' (line 22 was the super.method_missing line in the SaysGoodbye module)
It outputs correctly, then throws an error. Also respond_to? doesn't correctly, ObjectC.new.respond_to? :hello_a returns false.
Finally, adding this class:
class ObjectD
include SaysHello
include SaysGoodbye
def respond_to?(method)
super.respond_to?(method) || !!(method.to_s =~ /^lol/)
end
def method_missing(method, *args, &block)
if (method.to_s =~ /^lol/)
puts "Haha, #{method}"
else
super.method_missing(method, *args, &block)
end
end
end
Also acts strangely. ObjectD.new.lol_zzz works, however ObjectD.new.hello_aand ObjectD.new.goodbye_t both throw a name exception after outputting the correct string. respond_to? also fails for hello and goodbye methods.
Is there a way to get this all working correctly? An explanation of how method_missing, Modules and super are interacting would also be really useful.
EDIT: coreyward solved the problem, if I use super instead of super.<method-name>(args...) in all the methods I define, the program works correctly. I don't understand why this is though, so I asked another question about this at What does super.<method-name> do in ruby?
When you redefine a method, you redefine a method; period.
What you're doing when you include the second module with the method_missing method define is overriding the previously defined method_missing. You can keep it around by aliasing it before you redefine it, but you might want to watch out with that.
Also, I don't know why you're calling super.method_missing. Once your method_missing definition is out of tricks you should let Ruby know it can continue on up the chain looking for a way to handle the call, all just by calling super (no need to pass arguments or specify a method name).
About Super (update)
When you call super Ruby continues on up the inheritance chain looking for the next definition of the method invoked, and if it finds one it calls it and returns the response. When you call super.method_missing you call the method_missing method on the response to super().
Take this (somewhat silly) example:
class Sauce
def flavor
"Teriyaki"
end
end
# yes, noodles inherit from sauce:
# warmth, texture, flavor, and more! ;)
class Noodle < Sauce
def flavor
sauce_flavor = super
"Noodles with #{sauce_flavor} sauce"
end
end
dinner = Noodle.new
puts dinner.flavor #=> "Noodles with Teriyaki sauce"
You can see that super is a method just like any other, it just does some magic behind the scenes. If you call super.class here you're going to see String, since "Teriyaki" is a string.
Make sense now?
http://www.perfectline.ee/blog/activerecord-method-missing-with-multiple-inheritance
This article explains exactly how it works: Each new module doesn't overwrite or replace methods - instead, its methods are inserted into the inheritance chain. That's why calling super from each method_missing eventually calls all the method_missing's.
The class remains lowest in the inheritance chain, and the last-added module is adjacent to the class.
So:
class Foo
include A
include B
end
results in Kernel -> A -> B -> Foo

When an instance method calls a class method, I have to use self.class_method?

I'm getting an error so I guess I have to reference a class method from inside of an instance method with self.class_method_name, but why is that?
Shouldn't it resolve this by itself? Confused.
def self.blah(string)
..
end
def some_method()
some_thing = blah("hello")
end
If you have
# This won't work
class Foo
def self.blah(string)
puts "self.blah called with a string of #{string}"
end
def some_method
# This won't work
self.blah("hello")
end
end
foo = Foo.new
foo.some_method
It won't work, because it'll look for the instance method Foo#blah. Instead, you're looking for Foo.bar.
To make some_method call Foo.bar, you have to make some_method refer to the Foo class, and then call blah on it.
class Foo
def self.blah(string)
puts "self.blah called with a string of #{string}"
end
def some_method
# This will work
self.class.blah("hello")
end
end
foo = Foo.new
foo.some_method
The reason you have def self.blah to define the method, but self.class.blah to call the method, is that in the former, self refers to the Foo class, while in the latter, self refers to the foo object, so you need self.class to refer to the Foo class.
It may be easier to think of self as part of the method name, that way it's clear that you never defined a blah method, you defined only a self.blah method. (To clarify: the previous sentence shouldn't be thought of too much, so please don't read into it, as it's not how things are actually working, just a sort of "layman's terms" attempt at describing why it doesn't work.)
Also, what if you had defined a blah instance method in addition to the class method? If calling blah was enough to access the class method, how would you call the instance method?
Finally, there really isn't any such thing as a class method in Ruby, "class methods" are really methods of the singleton class.

How do I wrap the invocation of a Ruby method by including a module?

I want to be notified when certain things happen in some of my classes. I want to set this up in such a way that the implementation of my methods in those classes doesn't change.
I was thinking I'd have something like the following module:
module Notifications
extend ActiveSupport::Concern
module ClassMethods
def notify_when(method)
puts "the #{method} method was called!"
# additional suitable notification code
# now, run the method indicated by the `method` argument
end
end
end
Then I can mix it into my classes like so:
class Foo
include Notifications
# notify that we're running :bar, then run bar
notify_when :bar
def bar(...) # bar may have any arbitrary signature
# ...
end
end
My key desire is that I don't want to have to modify :bar to get notifications working correctly. Can this be done? If so, how would I write the notify_when implementation?
Also, I'm using Rails 3, so if there are ActiveSupport or other techniques I can use, please feel free to share. (I looked at ActiveSupport::Notifications, but that would require me to modify the bar method.)
It has come to my attention that I might want to use "the Module+super trick". I'm not sure what this is -- perhaps someone can enlighten me?
It has been quite a while since this question here has been active, but there is another possibility to wrap methods by an included (or extended) Module.
Since 2.0 you can prepend a Module, effectively making it a proxy for the prepending class.
In the example below, a method of an extended module module is called, passing the names of the methods you want to be wrapped. For each of the method names, a new Module is created and prepended. This is for code simplicity. You can also append multiple methods to a single proxy.
An important difference to the solutions using alias_method and instance_method which is later bound on self is that you can define the methods to be wrapped before the methods themselves are defined.
module Prepender
def wrap_me(*method_names)
method_names.each do |m|
proxy = Module.new do
define_method(m) do |*args|
puts "the method '#{m}' is about to be called"
super *args
end
end
self.prepend proxy
end
end
end
Use:
class Dogbert
extend Prepender
wrap_me :bark, :deny
def bark
puts 'Bah!'
end
def deny
puts 'You have no proof!'
end
end
Dogbert.new.deny
# => the method 'deny' is about to be called
# => You have no proof!
I imagine you could use an alias method chain.
Something like this:
def notify_when(method)
alias_method "#{method}_without_notification", method
define_method method do |*args|
puts "#{method} called"
send "#{method}_without_notification", args
end
end
You do not have to modify methods yourself with this approach.
I can think of two approaches:
(1) Decorate the Foo methods to include a notification.
(2) Use a proxy object that intercepts method calls to Foo and notifies you when they happen
The first solution is the approach taken by Jakub, though the alias_method solution is not the best way to achieve this, use this instead:
def notify_when(meth)
orig_meth = instance_method(meth)
define_method(meth) do |*args, &block|
puts "#{meth} called"
orig_meth.bind(self).call *args, &block
end
end
The second solution requires you to use method_missing in combination with a proxy:
class Interceptor
def initialize(target)
#target = target
end
def method_missing(name, *args, &block)
if #target.respond_to?(name)
puts "about to run #{name}"
#target.send(name, *args, &block)
else
super
end
end
end
class Hello; def hello; puts "hello!"; end; end
i = Interceptor.new(Hello.new)
i.hello #=> "about to run hello"
#=> "hello!"
The first method requires modifying the methods (something you said you didn't want) and the second method requires using a proxy, maybe something you do not want. There is no easy solution I'm sorry.

How to make a base class method non-overridable in ruby?

I have some base class A with a method that is not to be overridden.
class A
def dont_override_me
puts 'class A saying, "Thank you for not overriding me!"'
end
end
And another class B that extends A and tries to override the dont_override_me method.
class B < A
def dont_override_me
puts 'class B saying, "This is my implementation!"'
end
end
If I instantiate B and call dont_override_me, class B's instance method will be called.
b = B.new
b.dont_override_me # => class B saying, "This is my implementation!"
This is because of ruby's properties. Understandable.
However, how do I force the base class method dont_override_me to be non-overridable by it's derived classes? I could not find a keyword like final in java for ruby. In C++, the base class methods can be made non-virtual so that they become non-overridable by the derived classes. How do I achieve this in ruby?
You can do it, by hooking the change event and changing it back, but it seems a bit smelly to me:
http://scie.nti.st/2008/9/17/making-methods-immutable-in-ruby
It's one of those things that sort of defines Ruby, so fighting against it seems a little pointless imo. If someone redefines something so it breaks horribly.. that's their problem ;-)
Here's a way to do it:
http://www.thesorensens.org/2006/10/06/final-methods-in-ruby-prevent-method-override/
This has also been packaged into a gem called "finalizer" (gem install finalizer)
This makes use of the method_added callback and compares the new method name with a list of methods that you wish to make final.
I recommend:
class A #This is just as you've already defined it.
def dont_override_me
puts 'class A saying, "Thank you for not overriding me!"'
end
end
module BehaviorForB
def dont_override_me
puts 'class B saying, "This is my implementation!"'
end
def greet
"Hello, Friend."
end
end
class B < A
include BehaviorForB
end
b = B.new
b.dont_override_me #=> class A saying, "Thank you for not overriding me!"
b.greet #=> Hello, Friend.
By keeping B's methods tucked away in an mixin, you get exactly what you desire. Any method of B's methods that are not already in A will be available. Methods that are already in A will not be overridden.
One way to prevent a method from being overridden by a subclass (but not recommend) :
class Class
def frozen_method(method)
if class_variable_defined?(:##__frozen_methods__)
add= class_variable_get(:##__frozen_methods__) | [method]
class_variable_set(:##__frozen_methods__,add)
else
class_variable_set(:##__frozen_methods__,[method])
end
class << self
def inherited(child)
def method_added(method)
if class_variable_get(:##__frozen_methods__).include? method
send(:remove_method, method)
error="Cannot change method #{method} because it's not overridde"
raise TypeError, error
end
end
end
end
end
end
class Foo
def hello
'hello'
end
def foo
'foo'
end
frozen_method :foo
end
class Bar < Foo
def foo
'new foo'
end
end
#=> TypeError: Cannot change method foo because it's not overridde
Bar.new.foo #=> 'foo'
Warning: this example is not complete. If you add frozen_method for a previously defined method in the subclass, when this method will be modified in the subclass, it will lose its implementation.

Resources