创建一个简单的 Rails 3 文本助手 Gem
我一直在开发我的第一个 Rails 3 插件,以打包一个简单的辅助函数,我喜欢在我所有应用程序的 ApplicationHelper
中使用该函数。您可以在 Github 上查看完整代码。
这是我的第一次尝试:
## lib/semantic_id.rb ##
require 'semantic_id/version'
module ::ActionView::Helpers::TextHelper
def semantic_id
string = String.new
case
when controller.action_name =~ /new|edit/
string += controller.action_name + "_"
when controller.action_name =~ /index|create/
string += controller.controller_name
else
string += controller.controller_name.singularize
end
string += "_view"
end
end
现在,这可行,但据我了解,这不是扩展 ActiveSupport 或任何其他 Rails 模块的“Rails 3 Way”。我还没有找到太多关于如何“应该”构建 Rails 3 gem 的文档。我尝试遵循Rails Guide,但是那里给出的添加助手的方法不起作用,或者我错过了一些东西。
我的问题是:将上面的代码作为我正在寻找的功能的示例,您如何将其转换为 Rails 3 插件 Gem?
谢谢!
I've been working on my first Rails 3 plugin, to package up a simple helper function that I like having in the ApplicationHelper
of all my apps. You can see the whole code on Github.
Here's my first attempt:
## lib/semantic_id.rb ##
require 'semantic_id/version'
module ::ActionView::Helpers::TextHelper
def semantic_id
string = String.new
case
when controller.action_name =~ /new|edit/
string += controller.action_name + "_"
when controller.action_name =~ /index|create/
string += controller.controller_name
else
string += controller.controller_name.singularize
end
string += "_view"
end
end
Now, this works, but as I understand it this is not the 'Rails 3 Way' of extending ActiveSupport or any other Rails module. I haven't been able to find much documentation on how you're "supposed" to build a Rails 3 gem. I tried following the Rails Guide, but the method given there for adding helpers didn't work, or else I was missing something.
My question is: given the code above as an example of the functionality I'm looking for, how would you turn this into a Rails 3 plugin Gem?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您所做的事情的问题在于您已将 gem 的功能绑定到 ActionView。让它更通用会更好。
要解决此问题,您应该将代码打包到其自己的模块中,然后将该模块注入到您的视图环境中。例如,将您的帮助程序放入其自己的模块(和文件)中:
然后使用 Railtie 将其添加到 ActionView:
您希望将帮助程序的功能部分与将其插入框架的部分分开。您的方法包含一些特定于 Rails 的代码,但如果没有,此技术也允许您将其与 Sinatra 和其他框架一起使用。
一般来说,项目的核心内容应该位于
lib//*.rb
中,而lib/.rb
应该只提供功能可以访问。The problem with what you've done is that you've bound your gem's functionality to ActionView. It would be better to make it more generic.
To fix this you should package your code in its own module and then inject that module into your view environment. For example, put your helper into its own module (and file):
Then add it to ActionView using a Railtie:
You want to separate the functional part of the helper from the part that inserts it into the framework. Your method contains some Rails-specific code, but if it didn't this technique would allow you to use it with Sinatra and other frameworks as well.
In general, the guts of your project should be in
lib/<project_name>/*.rb
, andlib/<project_name>.rb
should just make the functionality accessible.