0

I'm working on a gem that does some general string manipulations I'd like to expose as helper methods to rails 4+ apps.

Not all consumers of my gem are rails apps so i'd like to safely expose helper methods to rails apps.

Two questions:

  1. How do I add view helper methods to Rails from a gem and where should it live within the gem directory structure?
  2. What can i do to prevent a blow up when the consumer is NOT a rails app? i.e. the gem can't find rails when it's included

Thanks

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
SharkLaser
  • 713
  • 1
  • 10
  • 19

2 Answers2

3

In your lib/my_gem.rb, you typically want to do something along these lines:

require 'my_gem/action_methods' if defined? ActionView

And lib/my_gem/action_view_methods.rb would contain all if your methods that require Rails/ActionView.

You can add these helpers to Rails with:

module ActionMethods
  # ...
end

ActionView::Base.send :include, ActionMethods

Also see this question, and this one.

Community
  • 1
  • 1
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
0

The rails way is by creating an engine and as it gets loaded with your gem it gets processed by rails

module MyGem
  class Engine < ::Rails::Engine
    isolate_namespace MyGem

    initializer "my_gem.include_view_helpers" do |app|
      ActiveSupport.on_load :action_view do
        include MyViewHelper
      end
    end
  end
end

Another way you can go is to not include the helper by default so that consumers don't get unexpected side-effects from your gem. Create the helper as a module and document that it should be added to ApplicationController or any needed controller.

rafb3
  • 1,694
  • 12
  • 12