Thursday, February 19, 2015

Using self.included to Include Dependencies

As part of a project I'm working on, I created a mountable engine for extracting all authentication concerns for the app. I created a TestHelper module that includes methods for mocking various aspects required for authentication. These methods require Devise::TestHelpers to function properly, and my goal was for the calling app to not know or care about this dependency. To solve this, I used self.included to automatically include the helper when necessary (in my case, only in controller specs).
Here is the code:

 def self.included(receiver)  
  if defined?(receiver.metadata) && receiver.metadata[:type] == :controller  
   receiver.send :include, Devise::TestHelpers  
  end  
 end  

No comments:

Post a Comment