Kishore Mohan
Kishore Mohan

Reputation: 1060

application helper method invoking in another helper

I am stuck in a weird Design problem,

I'm facing issues when I'm trying to invoke a application helper method in another helper which have multiple class and want to access application helper method.

what is the better approach?

Thoughts about what can I do?

my code looks similar like this,


## app/helpers/application_helper.rb
module ApplicationHelper
  def my_name
    "stackoverflow"
  end
end

Another helper with sub classes


## app/helpers/my_helper.rb
module MyHelper
  class MyTestclass
    def want_myname
      my_name ## giving undefined method-- how can i call myname method here?
    end
  end
end

undefined method `myname' for MyHelper::MyTestclass

Upvotes: 0

Views: 2061

Answers (1)

Abdul Baig
Abdul Baig

Reputation: 3721

Here is a brief explanation of your problem and how to use modules: To 1. A module is created/opened by simply saying:

module MyModule
  def first_module_method
  end
end

To 2. The lib folder. If you want to organize your modules in the lib folder, you can put them into modules themselves. For example, if you wanted a subfolder super_modules your modules would be defined as follows:

module SuperModules
  module MyModule
    def first_module_method
    end
  end

end

To 3./5. When including the module in a class you can simply call the modules methods as if they were defined within the class:

class MyClass
  include MyModule
  def some_method
    first_module_method #calls module method
  end
end

To 4. Frst, make sure that your module is really needed in every class of your application. If it isn't it makes sense to only include it where it is need so as not to bloat the classes that don't need it anyways. If you really want the module everywhere, include look at the class hierarchy of your classes in the app. Do you want the module in all models? You could open ActiveRecord::Base and add add your module there.

Upvotes: 1

Related Questions