Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - How to redefine class methods?

Tags:

ruby

How do I redefine a class method in ruby?

say, for example, I want to redefine the method File.basename("C:\abc.txt") How do I do it?

This doesn't work:

class File
  alias_method :old_bn, :basename

  def basename(*args)
    puts "herro wolrd!"
    old_bn(*args)
  end
end

I get : undefined method 'basename' for class 'File' (NameError)

btw, I'm using JRuby

like image 583
RubyDosa Avatar asked Mar 22 '11 09:03

RubyDosa


People also ask

How do you override a class in Ruby?

Override means two methods having same name but doing different tasks. It means that one of the methods overrides another method. If there is any method in the superclass and a method with the same name in its subclass, then by executing these methods, method of the corresponding class will be executed.

How do you define a class method in Ruby?

There are two standard approaches for defining class method in Ruby. The first one is the “def self. method” (let's call it Style #1), and the second one is the “class << self” (let's call it Style #2). Both of them have pros and cons.

Does method order matter in Ruby?

You could define method in any order, the order doesn't matter anything.

What does it mean when a method ends with in Ruby?

Ruby doesn't treat the ! as a special character at the end of a method name. By convention, methods ending in ! have some sort of side-effect or other issue that the method author is trying to draw attention to.


2 Answers

alias_method is meant for instance methods. But File.basename is a class method.

class File
  class << self
    alias_method :basename_without_hello, :basename

    def basename(*args)
      puts "hello world!"
      basename_without_hello(*args)
    end
  end
end

The class << self evaluates everything on the "class level" (Eigenklass) - so you don't need to write self. (def self.basename) and alias_method applies to class methods.

like image 142
Marcel Jackwerth Avatar answered Oct 17 '22 11:10

Marcel Jackwerth


class << File
  alias_method :old_bn, :basename
  def basename(f)
    puts "herro wolrd!"
    old_bn(*args)
  end
end
like image 20
Jakub Hampl Avatar answered Oct 17 '22 10:10

Jakub Hampl