【问题标题】:undefined method `hashtag_url' for class `Module'类“模块”的未定义方法“hashtag_url”
【发布时间】:2023-03-17 02:39:01
【问题描述】:

我在 StackOverflow 和 Google 中寻找了很多东西,但我找不到任何解决我的问题的方法。我正在尝试覆盖 Twitter-text gem 中的一个方法,但我认为它比这要复杂一些。

我编辑了 Twitter 文本 gem 并创建了一个新的以在我的项目中使用。在这个新的 gem 中,我改变了一些东西,并在 Autolink 模块中添加了一个名为“hashtag_url”的方法。

def hashtag_url(hashtagName) 

end 

我称之为“hashtag_url”的方法是这样的(这个方法也在gem上):

def link_to_hashtag(entity, chars, options = {})
    (...)

     href = hashtag_url(hashtag)
end

Hashtag_url 是空白的,因为我需要访问我的数据库,所以,我只是在 Twitter::Autolink 模块中声明了这个方法,并想在我的项目中覆盖这个方法。现在,让我们看一下我的项目的代码。我遵循了一些stackoverflow问题的提示,得到了这个结果:

/lib/ritter.rb(只是一种测试方法)

require 'ritter'

Twitter::Autolink::ClassMethods.module_eval do
    def hashtag_url(hashtagName)
        puts "I think I can't do that..."
        if hashtag = Hashtag.find_by_name(hashtagName)
            puts "I'm ok guys!"
            return "http://localhost:3000/hashtags/#{hashtag.slug}"
        end
    end
end

当我尝试检查方法是否被覆盖时,我在 Rails 控制台中使用它:

Twitter::Autolink.method(:hashtag_url).source_location

我得到了:

NameError: undefined method `hashtag_url' for class `Module'
    from (irb):1:in `method'
    from (irb):1
    from /usr/lib/ruby/gems/1.9.1/gems/railties-3.2.3/lib/rails/commands/console.rb:47:in `start'
    from /usr/lib/ruby/gems/1.9.1/gems/railties-3.2.3/lib/rails/commands/console.rb:8:in `start'
    from /usr/lib/ruby/gems/1.9.1/gems/railties-3.2.3/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

P.S:我不会在任何地方调用、要求或包含“Ritter.rb”,我需要这样做吗?我的 Ritter.rb 是在正确的路径上,这里面的代码是对的吗?我该如何解决这个问题?

如有必要,我可以更多地谈论我为什么需要数据库。谢谢,欢迎任何评论和回答!

【问题讨论】:

  • 乍一看:if hashtag = ..一定是if hashtag == ..
  • @ovhaag ,但我认为你错了。 “hashtag”不存在,之前甚至没有声明或使用过。我将方法的值分配给这个变量,如果它是真的,我返回“localhost:3000/hashtags/#{hashtag.slug}”。我正在做一个作业,然后通过比较 if。但是感谢您的回复(:
  • 我的错误。也许我现在做下一个,因为我不熟悉元编程。但只是一个想法。您似乎想向 Twitter::Autolink 添加一个方法。你不应该直接在 Twitter::Autolink 上调用 module_eval 吗?即:Twitter::Autolink.module_eval do ..
  • @ovhaag 这解决了我的问题朋友,谢谢!发布为官方答案,我会给你正确的答案!再次,非常感谢!

标签: ruby-on-rails ruby methods overriding


【解决方案1】:

如果你想给Twitter::Autolink添加一个方法,你应该直接在Twitter::Autolink上调用module_eval

Twitter::Autolink.module_eval do 
  # ..
end

【讨论】:

  • 非常感谢@ovhaag haha​​hahah!
猜你喜欢
  • 2015-01-22
  • 2020-04-04
  • 2012-04-14
  • 2011-11-19
  • 1970-01-01
  • 1970-01-01
  • 2011-04-06
  • 2011-01-14
  • 1970-01-01
相关资源
最近更新 更多