Best ruby-on-rails-3.1 questions in March 2012

How to use modules in Rails application

5 votes

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

You might have to restart the rails server for it to recognize stuff in the lib directory.