如何将 Rails 视图助手提取到 gem 中? [英] How do I extract Rails view helpers into a gem?

查看:28
本文介绍了如何将 Rails 视图助手提取到 gem 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组经常使用的 rails 视图助手,我想将它们打包成一个 gem,这样我就可以在我的 Gemfile 中放一行,并且可以从我的视图中访问这些助手.

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.

在使用 Bundler 和 Jeweler 之前,我已经创建了 gem,但是,我并不是很清楚如何在 gem 中组织 Rails 视图助手,并将它们包含到 rails 中.

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.

如果您能提供有关如何为 Rails 3 执行此操作的任何指示或指向最新教程的链接,我将不胜感激

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

谢谢

澄清一下:问题不在于如何创建宝石".它是如何将视图助手打包到 gem 中,以便我可以在 Rails 中使用它们"

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"

我也同意下面的海报.. 对于这种(希望是简单的)需求来说,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

推荐答案

在我看来,一个完整的 引擎 对于这项任务来说太过分了.您可以改为创建一个 Railtie 将您的助手包含到 ActionView::Base 中初始化时.

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
      ActiveSupport.on_load(:action_view) { include MyGem::ViewHelpers }
    end
  end
end

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

这篇关于如何将 Rails 视图助手提取到 gem 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆