【问题标题】:Rails using custom helper in config fileRails 在配置文件中使用自定义助手
【发布时间】:2014-05-21 08:53:36
【问题描述】:

我有一个自定义助手:

module PostsHelper
    def post_path(post)
        year = post.published_at.year

        month = post.published_at.month
        month = "0#{ month }" if month < 10

        day = post.published_at.day
        day = "0#{ day }" if day < 10

        "#{ blog_path }/#{ year }/#{ month }/#{ day }/#{ post.raw_title }"
    end
end

我想在我用来构建站点地图的 config/sitemap.rb 文件中使用帮助程序。

我正在文件中尝试这个:

Post.posts.each do |bp|
    add PostsHelper::post_path(bp), priority: 1, changefreq: 'weekly'
end

但我不断收到此错误:

NoMethodError: undefined method `post_path' for PostsHelper:Module

尝试包含该模块也无济于事 (include PostsHelper):

NoMethodError: undefined method `include' for #<SitemapGenerator::Interpreter:0x000000025086b8> 

如何在配置文件中使用自定义 Rails 助手?

【问题讨论】:

  • 您在类级别调用post_path,而它是在实例级别定义的;试试def self.post_path(post)
  • @mdesantis 好的,我同意,但是如何在实例级别调用它?这才是我真正想做的事
  • 也许你应该了解更多关于Ruby modules
  • 问题是如果我打电话给include PostsHelper 我得到这个:NoMethodError: undefined method `include' for #&lt;SitemapGenerator::Interpreter:0x000000025086b8&gt;
  • 哦,你指的是配置文件,对不起,我没明白

标签: ruby-on-rails


【解决方案1】:

您必须在 config/sitemap.rb 中包含帮助程序模块

将此添加到config/sitemap.rb 文件的顶部

SitemapGenerator::Interpreter.send :include, PostsHelper

【讨论】:

    猜你喜欢
    • 2016-01-29
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2011-03-16
    • 2021-01-26
    • 2015-08-11
    相关资源
    最近更新 更多