[英]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 . 我在我的项目中使用Twitter-text gem,但是我遇到了一些错误 。 I need override one constant of that gem. 我需要覆盖那个gem的一个常量。
I see some questions on StackOverflow about method override that helped me, but I'm still having troubles. 我在StackOverflow上看到一些关于方法覆盖的问题对我有帮助,但我仍然遇到麻烦。 I created a file called twitter-text.rb
in /config/initializers/
and wrote the following code: 我在/config/initializers/
创建了一个名为twitter-text.rb
的文件,并编写了以下代码:
module Twitter
class Regex
HASHTAG_CHARACTERS = "/[[^ ]_#{LATIN_ACCENTS}]/io"
end
end
(this Regex allows me to write Hashtags with any characters except blank spaces). (这个正则表达式允许我用除空格之外的任何字符编写Hashtags)。
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
. 我刚刚在这个方法中添加了以下行: text = text.downcase
。 Well, what can I do to override this method and attribute/constant? 那么,我该怎么做才能覆盖这个方法和属性/常量?
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. 不过,这是一个超级丑陋的monkeypatch领域。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.