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

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

问题描述

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

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

我很感谢任何指针,或者链接到最新的教程,了解如何为Rails 3做到这一点。



谢谢

澄清:问题不在于如何创建宝石。它的如何在gem中封装视图助手,所以我可以在Rails中使用它们。

编辑2:
我也同意下面的海报..对于这种(希望很简单)的要求,一个rails引擎是多余的矫枉过正

在我看来,一个完整的引擎对于这项任务是矫枉过正的。你可以改为创建一个 Railtie ,其中包括你的助手进入ActionView :: Base当它初始化时。

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

def another_helper
#超级秘密东西
结束
结束
end

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

$ lib / my_gem.rb
如果定义了需要'my_gem / railtie'?(Rails)


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

解决方案

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)

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

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