When do you use aliasing?

Are you using an alias method to add more methods to call methods (e.g. length and size), or is there another use for this?

+3
source share
2 answers

The alias_method call is also useful for reimplementing something, but preserving the original version. There is also alias_method_chain from Rails, which makes this even easier.

alias_method is also useful when you have several behaviors that are initially identical, but may diverge in the future, where you can at least start them.

def handle_default_situation
  nil
end

%w[ poll push foo ].each do |type|
  alias_method :"handle_#{type}_situation", :handle_default_situation
end
+3
source

Yes.

It is often used to store the descriptor of existing methods before overriding them. (far-fetched example)

, :

class Foo
  def do_something
    puts "something"
  end
end

, :

class Foo
  def do_something_with_logging
    puts "started doing something"
    do_something_without_logging # call original implementation
    puts "stopped doing something"
  end

  alias_method :do_something_without_logging, :do_something
  alias_method :do_something, :do_something_with_logging
end

( alias_method_chain)

.

, alias_method - , ( - alias_method_chain)

+3

Source: https://habr.com/ru/post/1716339/


All Articles