In Rails, how to add a new method to String class?

ぐ巨炮叔叔 提交于 2019-11-27 03:23:14

You can define a new class in your application at lib/ext/string.rb and put this content in it:

class String
  def to_magic
    "magic"
  end
end

To load this class, you will need to require it in your config/application.rb file or in an initializer. If you had many of these extensions, an initializer is better! The way to load it is simple:

require 'ext/string'

The to_magic method will then be available on instances of the String class inside your application / console, i.e.:

>> "not magic".to_magic
=> "magic"

No plugins necessary.

I know this is an old thread, but it doesn't seem as if the accepted solution works in Rails 4+ (at least not for me). Putting the extension rb file in to config/initializers worked.

Alternatively, you can add /lib to the Rails autoloader (in config/application.rb, in the Application class:

config.autoload_paths += %W(#{config.root}/lib)

require 'ext/string'

See this: http://brettu.com/rails-ruby-tips-203-load-lib-files-in-rails-4/

When you want to extend some core class then you usually want to create a plugin (it is handy when need this code in another application). Here you can find a guide how to create a plugin http://guides.rubyonrails.org/plugins.html and point #3 show you how to extend String class: http://guides.rubyonrails.org/plugins.html#extending-core-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!