开发者

Using class function from the lib directory in rails

开发者 https://www.devze.com 2023-01-22 03:08 出处:网络
I am creating a rails3 application and I want to create a class that handles string formatting, so I made a class called FormatUtilites.rb in the lib d开发者_高级运维irectory but whenever I try callin

I am creating a rails3 application and I want to create a class that handles string formatting, so I made a class called FormatUtilites.rb in the lib d开发者_高级运维irectory but whenever I try calling it from somewhere else in my app I get this error:

ActionView::Template::Error (uninitialized constant ActionView::CompiledTemplates::FormatUtilities)

So it thinks its a constant and not a class method, which is how it is defined. Any ideas?

class FormatUtilities

  def self.slugify(name)
    name.downcase.gsub(/\s|\W|\D/, "")
  end

end

Thanks!


Turns out rails3 stop autoloading the lib directory. I have no idea why they did it, but they did. Just needed to add it to the autoload in the application.rb

thanks anyways!


Classes are constants in Ruby, besides also being classes. Probably you just need to do "require format_utilities"


You need to add:

# in config/application.rb
config.autoload_paths = %W(#{config.root}/lib

The name of your file should be format_utilities.rb for autoload to work.

In your particular case i would use a different aproach. Instead of creating a class with static functions i would create a module named FormattingHelper in app/helpers/formatting_helper.rb like this.

class FormattingHelper
  def slugify(name)
    name.downcase.gsub(/\s|\W|\D/, "")
  end
end

Then in ApplcationController or in a specific controller i would add:

class ApplicationController < ActionController::Base
  helper :formatting
end


If you want rails to automatically load this file when it boots, you will need to name your file format_utilities.rb. The next time you restart your server or console, you should be able to do FormatUtilities.slugify("name")

0

精彩评论

暂无评论...
验证码 换一张
取 消