Note that there are some explanatory texts on larger screens.

plurals
  1. POAccess controller method in a Ruby module
    text
    copied!<p>In my Rails app, there is a method defined in the ApplicationController that I need to use in a module. This module also needs to be accessible to all controllers/helpers. I'm not sure what the best way is to give the module access to this method. I figure that there is a way to do it by wrapping the module and then including it into the ApplicationController. </p> <p>I also want to retain the namespacing instead of including the module methods right into the controller. e.g. controller.Module.foo instead of just controller.foo</p> <p>This is what I'm trying to do:</p> <pre><code>module Analytics module Events extend self def create_event name # do some stuff controller_method name end end end class ApplicationController &lt; ActionController::Base include Analytics def controller_method # ... end def some_other_method Events.create_event :test end end </code></pre> <p>Now I know I can add a self.included method to the Analytics module which gives me the passed in base object, but I don't know how I can make use of that base in the KissMetrics module.</p> <p>Is this possible or is there a better way of doing this?</p> <h2>Edit:</h2> <p>To further clarify, I am using a gem that is extended/included into ActionController::Base. See bottom of this <a href="https://github.com/jkrall/analytical/blob/master/lib/analytical.rb" rel="nofollow">script</a>. This library is then configured inside the ApplicationController. All I want to do is have a module with defined events that makes use of this gem. It makes it easier for me to have consistent events across all my controllers e.g.</p> <pre><code>module Events def sign_up_event analytical.event "sign up" # calls the library that was loaded into the app controller end end # in some controller Events.sign_up_event # instead of this, which is totally usable but not DRY analytical.event "sign up" </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload