Rails:无法访问我的 lib 目录中的模块 [英] Rails: Can't access a module in my lib directory

查看:37
本文介绍了Rails:无法访问我的 lib 目录中的模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个通用字符串操作类,可以在我的 Rails 应用程序中跨模型、视图和控制器使用.

I'd like to create a general purpose string manipulation class that can be used across Models, Views, and Controllers in my Rails application.

现在,我正在尝试将一个模块放入我的 lib 目录中,我只是尝试访问 rails 控制台中的函数来测试它.我已经尝试了很多类似问题的技巧,但我无法让它发挥作用.

Right now, I'm attempting to put a Module in my lib directory and I'm just trying to access the function in rails console to test it. I've tried a lot of the techniques from similar questions, but I can't get it to work.

在我的 lib/filenames.rb 文件中:

In my lib/filenames.rb file:

module Filenames

  def sanitize_filename(filename)
    # Replace any non-letter or non-number character with a space
    filename.gsub!(/[^A-Za-z0-9]+/, ' ')

    #remove spaces from beginning and end
    filename.strip!

    #replaces spaces with hyphens
    filename.gsub!(/\ +/, '-')
  end

  module_function :sanitize_filename

end

当我尝试调用 sanitize_filename("some string") 时,出现无方法错误.当我尝试调用 Filenames.sanitize_filename("some string") 时,出现未初始化的常量错误.当我尝试包含/lib/filenames"时,出现加载错误.

When I try to call sanitize_filename("some string"), I get a no method error. When I try to call Filenames.sanitize_filename("some string"), I get an uninitilized constant error. And when I try to include '/lib/filenames' I get a load error.

  1. 这是创建我可以在任何地方访问的方法的最传统方法吗?我应该创建一个类吗?

  1. Is this the most conventional way to create a method that I can access anywhere? Should I create a class instead?

我怎样才能让它工作?:)

How can I get it working? :)

谢谢!

推荐答案

要获得真正好的答案,请查看您问题的评论中引用的 Yehuda Katz 的答案(实际上,请务必查看).

For a really great answer, look at Yehuda Katz' answer referenced in the comment to your question (and really, do look at that).

在这种情况下,简短的回答是您可能没有加载文件.请参阅 RyanWilcox 给您的链接.您可以通过在文件中添加语法错误来检查这一点 - 如果在启动应用程序(服务器或控制台)时未引发语法错误,您就知道文件没有被加载.

The short answer in this case is that you probably are not loading your file. See the link that RyanWilcox gave you. You can check this by putting a syntax error in your file - if the syntax error is not raised when starting your app (server or console), you know the file is not being loaded.

如果你认为你正在加载它,请发布你用来加载它的代码.同样,请参阅 RyanWilcox 给您的链接以了解详细信息.它包含此代码,该代码进入您的环境配置文件之一:

If you think you are loading it, please post the code you are using to load it. Again, see the link RyanWilcox gave you for details. It includes this code, which goes into one of your environment config files:

# Autoload lib/ folder including all subdirectories
config.autoload_paths += Dir["#{config.root}/lib/**/"]

但实际上,请阅读 Yehuda 的回答.

But really, read Yehuda's answer.

这篇关于Rails:无法访问我的 lib 目录中的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆