nish
nish

Reputation: 7280

How to write methods accessible by all views

I am working with rails 3.1.10. I want to write a couple of methods which I can call from any of the views. I found this question very helpful.

What I did: 1. created a module lib/unbxd_api.rb:

module UnbxdApi
    require 'net/http'

    def method1
    end

    def method2
    end
end
  1. In app/helpers/application_helper.rb

    module ApplicationHelper
        include UnbxdApi
    

But I am getting the following error:

`<module:ApplicationHelper>': uninitialized constant ApplicationHelper::UnbxdApi (NameError)

Why am I getting this error and how can i resolve it?

Upvotes: 0

Views: 78

Answers (2)

Nimir
Nimir

Reputation: 5839

Files in lib folder aren't autoloaded, you need to require your module

require 'unbxd_api'

module ApplicationHelper
  include UnbxdApi
end

Upvotes: 1

Surya
Surya

Reputation: 15992

That because Rails does not load lib directory anymore. You have to do that explicitly by saying:

config.autoload_paths += Dir["#{config.root}/lib/**/"]

inside your config/application.rb file.

Note: If you want a helper method that's available to all views file then I would suggest you to create helper UnbxdApiHelper instead inside app/helpers/unbxd_api_helper.rb.

Upvotes: 2

Related Questions