3

I have a 3rd party gem with extension for String class:

class String
  def to_url
    self.gsub /\s+/, '-'
  end
end

And I have my app trying to extend String class:

class String
  def to_url
    Russian.translit self
    super
  end
end

How do I call super (to replace spaces AND do transliteration) from my app? My code does super, but skips Russian.translit self.

ujifgc
  • 2,215
  • 2
  • 19
  • 21
  • 2
    This is largely a duplicate of [When monkey patching a method, can you call the overridden method from the new implementation](http://StackOverflow.Com/questions/4470108/when-monkey-patching-a-method-can-you-call-the-overridden-method-from-the-new-im/4471202/#4471202). – Jörg W Mittag Aug 09 '11 at 15:24

3 Answers3

3

There is no super to call. You should use alias_method

class String
  alias_method :old_to_url, :to_url
  def to_url
    Russian.translit(self).old_to_url
  end
end
Serabe
  • 3,834
  • 19
  • 24
0

I think that your Russian.translit self is working fine you are just not using the result. You should be using something like Russian.translit! self if Russian has such a method.

J Lundberg
  • 2,313
  • 2
  • 20
  • 23
  • Convention in Ruby is that bang methods modify the object they are called in. The string (self) is an argument, not the receiver. Furthermore, the to_url method from @ujifgc does not change the receiver, so I think doing so is a Bad Idea (TM) – Serabe Aug 09 '11 at 14:49
  • @Serabe I can dig that thanks for the heads up. Still new to Ruby myself. – J Lundberg Aug 09 '11 at 14:59
0

Yay! I found a way to call super for self (if there were a super). self cannot be assigned, but it's data can be replaced.

class String
  def to_url
    self.replace Russian.translit(self)
    super
  end
end
ujifgc
  • 2,215
  • 2
  • 19
  • 21