简体   繁体   中英

How do I make a lib module method available project-wide and also specific to a class in Ruby on Rails?

For example I would like to create a current_server_host method that returns the current host the application is currently running from.

lib/utility.rb:

module Utility
  def current_server_host
    request.env['HTTP_HOST']
  end
end

How do I make it available project-wide where I don't need to include anything but can just call via Utility.current_server_host ?

How do I make it specific to the class (model/controller/view) where I do need to call include ?

Please answer for RoR 3.2+.

Thanks!

To make Utility methods available as class methods in another class, use extend:

class Widget
  extend Utility
end

# provides
Widget.current_server_host

A ruby module can extend itself in the same manner in which it can extend classes:

module Utility
  extend self

  def current_server_host
    request.env['HTTP_HOST']
  end
end

# provides
Utility.current_server_host

If you want to provide Utility methods to instances of a class, use include:

class Widget
  include Utility
end

widget = Widget.new
widget.current_server_host

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM