How do I extract Rails view helpers into a gem?

允我心安 提交于 2019-11-26 15:13:22

问题


I have a set of rails view helpers that I use regularly, and would like to package them up into a gem, such that I could just put a line in my Gemfile, and have the helpers accessible from my views.

I have created gems before using Bundler, and Jeweler, however, I'm not all all clear on how to organize the Rails view helpers in a gem, and include them into rails.

I would appreciate any pointers, or links to up-to-date tutorials on how to do this for Rails 3

Thanks

Just to clarify: The question isn't on "how to create a gem". Its "how to package view helpers in a gem, so I can use them in Rails"

Edit 2: I also agree with the poster below.. A rails engine is waay too much overkill for this kind of (hopefully simple) requirement


回答1:


In my opinion, a full Engine is overkill for this task. You could instead just create a Railtie which includes your helpers into ActionView::Base when it initializes.

# lib/my_gem/view_helpers.rb
module MyGem
  module ViewHelpers
    def pre(text)
      content_tag :pre, text
    end

    def another_helper
      # super secret stuff
    end
  end
end

# lib/my_gem/railtie.rb
require 'my_gem/view_helpers'
module MyGem
  class Railtie < Rails::Railtie
    initializer "my_gem.view_helpers" do
      ActionView::Base.send :include, ViewHelpers
    end
  end
end

# lib/my_gem.rb
require 'my_gem/railtie' if defined?(Rails)



回答2:


Also if you want include helper only for Rails3 version you can use

# lib/my_gem.rb
require 'my_gem/railtie' if defined?(Rails::Railtie)



回答3:


What you are probably looking for is an engine. An engine is a gem that contains rails application pieces (in fact, a rails application is itself an engine.)



来源:https://stackoverflow.com/questions/5791211/how-do-i-extract-rails-view-helpers-into-a-gem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!