I just created a module location.rb inside /lib folder with following contents:
module Location
def self.my_zipcode()
zip_code = "11215"
end
end
And now in my controller i am trying to call "my_zipcode" method:
class DirectoryController < ApplicationController
def search
require 'location'
zip_code = Location.my_zipcode()
end
end
But it throws an error:
undefined method `my_zipcode' for Location:Module
Modules provide a structure to collect Ruby classes, methods, and constants into a single, separately named and defined unit. This is useful so you can avoid clashes with existing classes, methods, and constants, and also so that you can add (mix in) the functionality of modules into your classes.
You can include a module in a class in your Rails project by using the include keyword followed by the name of your module. Now you should be able to do Customer. new. hello and get “hello” as a result.
A Module is a collection of methods, constants, and class variables. Modules are defined as a class, but with the module keyword not with class keyword. Important Points about Modules: You cannot inherit modules or you can't create a subclass of a module. Objects cannot be created from a module.
A Ruby module is nothing more than a grouping of objects under a single name. The objects may be constants, methods, classes, or other modules. Modules have two uses. You can use a module as a convenient way to bundle objects together, or you can incorporate its contents into a class with Ruby's include statement.
You can also add the following to your config/application.rb
config.autoload_paths += %W(#{config.root}/lib)
And it should autoload your module without having to restart rails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With