Access url_helper from an Engine class

class, rails-engines, ruby-on-rails, urlhelper

Solution

Firstly, what you're not making clear is if the url helper you're trying to access is from the parent application the engine is added to, or if it's from another engine this engine has included.

If from parent application, then all you need is:

main_app.pages_url

So you'll need to edit your code accordingly. Note that the "main_app" part is not the name of the parent application but literally the words "main_app".

If you're trying to access a url helper of an engine that you included in this engine, then you need to access it like you would to access any engine from the parent application. I.e.:

Your gemspec file should include:

s.add_dependency('my_engine', path: "~/path/to/my_engine")

routes.rb should include:

mount MyEngine::Engine => "/my_engine", as: "any_name_for_my_engine"

and then access it in your code using:

any_name_for_my_engine.pages_url

Hope this helps.

EDIT: Change your engine's application.rb file to look as shown below, so that you can inherit all the parent application's ApplicationController variables and routes:

class Station::ApplicationController < ApplicationController
end

You might want to read the Rails Guide on Engines for a more detailed explanation on how to make these work together. Ask again if you're still having trouble.

Problem

I try to access URL helper from inside a Module class. Here's my code : ``` module Station class Plugins @@plugins = [] unless defined?(@@plugins) && @@plugins.class == Array class << self def all return @@plugins.sort_by { |p| p[:weight] } end def register(plugin = {}) raise "plugin must be a Hash (ie.: `register(:foo => 'bar')`)" unless plugin.class == Hash raise "plugin must contain :name (ie.: `register(:name => 'my_plugin')`)" unless plugin[:name].present? plugin[:weight] = 1 unless plugin[:weight].present? plugin[:href] = eval("#{plugin[:name].downcase.pluralize}_url") unless plugin[:href].present? @@plugins.push(plugin) unless @@plugins.include?(plugin) end end # include default plugins: Station::Plugins.register(:name => "Pages", :weight => -1) end end ``` When I run my server, I got this error back: ``` undefined local variable or method `pages_url' for Station::Plugins:Class ``` I read a lot about "how to call url helper from a Class", but none of the solutions I found worked for me.

Original source