Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override Constant of a gem? (Ruby on Rails)

I'm working with Twitter-text gem on my project, but I'm getting some errors. I need override one constant of that gem.

I see some questions on StackOverflow about method override that helped me, but I'm still having troubles. I created a file called twitter-text.rb in /config/initializers/ and wrote the following code:

module Twitter
  class Regex
    HASHTAG_CHARACTERS = "/[[^ ]_#{LATIN_ACCENTS}]/io"
  end
end

(this Regex allows me to write Hashtags with any characters except blank spaces).

I'm trying to override a method too, but it appears that doesn't work too. Following my code (on the same file):

module Twitter
  module Autolink
    def auto_link_hashtags(text, options = {})  # :yields: hashtag_text
      text = text.downcase
      options = options.dup
      (...)
    end
  end
end

I just added the following line to this method: text = text.downcase. Well, what can I do to override this method and attribute/constant?

like image 384
Paladini Avatar asked Jan 13 '23 15:01

Paladini


1 Answers

You could try removing the constant first, then redefining it:

module Twitter
  class Regex
    remove_const(:HASHTAG_CHARACTERS) if (defined?(HASHTAG_CHARACTERS))

    HASHTAG_CHARACTERS = "/[[^ ]_#{LATIN_ACCENTS}]/io"
  end
end

This is super-ugly monkeypatch territory, though.

like image 56
tadman Avatar answered Jan 17 '23 07:01

tadman