Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use modules in Rails application

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

like image 848
Tamik Soziev Avatar asked Mar 29 '12 00:03

Tamik Soziev


People also ask

What is the use of module in Rails?

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.

How do I add a module in Rails?

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.

What is module function in Ruby on Rails?

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.

How does module work in Ruby?

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.


1 Answers

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.

like image 73
outside2344 Avatar answered Sep 29 '22 12:09

outside2344