Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this deprecate method work?

I was trying to understand this call:

deprecate :new_record?, :new?

which uses this deprecate method:

   def deprecate(old_method, new_method)
      class_eval <<-RUBY, __FILE__, __LINE__ + 1
        def #{old_method}(*args, &block)
          warn "\#{self.class}##{old_method} is deprecated," + 
                "use \#{self.class}##{new_method} instead"
          send(#{new_method.inspect}, *args, &block)
        end
      RUBY
    end

I don't really understand the metaprogramming that's being used here. But, is this just another way of aliasing the new_record? method - so in effect, new_record? is still available but it issues a warning when you use it? Would anyone like to explain how this works?

like image 281
Hola Avatar asked Jun 21 '09 00:06

Hola


People also ask

How do you use deprecated method?

Using the @Deprecated Annotation To use it, you simply precede the class, method, or member declaration with "@Deprecated." Using the @Deprecated annotation to deprecate a class, method, or field ensures that all compilers will issue warnings when code uses that program element.

What is a deprecated method?

Similarly, when a class or method is deprecated, it means that the class or method is no longer considered important. It is so unimportant, in fact, that it should no longer be used at all, as it might well cease to exist in the future. The need for deprecation comes about because as a class evolves, its API changes.

Will deprecated methods work?

A deprecated class or method is like that. It is no longer important. It is so unimportant, in fact, that you should no longer use it since it has been superseded and may cease to exist in the future.

How do you deprecate in Java?

Use both @Deprecated annotation and the @deprecated JavaDoc tag. The @deprecated JavaDoc tag is used for documentation purposes. The @Deprecated annotation instructs the compiler that the method is deprecated.


1 Answers

ok, so what happens here is that all the functionality of old_method has been moved to new_method by the programmer. To make both names point to the same functionality but note the deprecation, the programmer puts in the deprecate line. This causes the string specified in the <-RUBY heredoc (http://en.wikipedia.org/wiki/Heredoc) to be interpreted as code (evaluated) at the class level. The string interpolations work just as they do in normal ruby strings.

The code then looks something like this (if we were to expand out the metaprogramming)

class SomeClass
  def new?; true; end

  deprecate :new_record?, :new? # this generates the following code

  def new_record?(*args, &block)
    warn "SomeClass#new_record? is deprecated," + 
            "use SomeClass#new? instead"
    send(:new?, *args, &block)
  end
end

I hope that makes sense

like image 170
Ben Hughes Avatar answered Oct 14 '22 06:10

Ben Hughes