简体   繁体   English

如何将ruby gem的代码包含到主rails项目中?

[英]How do I include a ruby gem's code into main rails project?

Let's say that I need to change the functionality of a certain ruby gem that I need in my rails project. 假设我需要在rails项目中更改我需要的某个ruby gem的功能。 I would like to place all the content of the ruby gem inside the main project. 我想将ruby gem的所有内容放在主项目中。

Is this possible? 这可能吗? Are there alternative methods? 有替代方法吗?

Thank you 谢谢

You can do this by "monkeypatching" the specific methods. 你可以通过“monkeypatching”具体方法来做到这一点。 To do this you need to create an initializer that overwrites the method you want to modify. 要执行此操作,您需要创建一个覆盖您要修改的方法的初始化程序。 For examplke create config/initializers/monkeypatch.rb and overwrite the method: 例如,创建config/initializers/monkeypatch.rb并覆盖该方法:

class String
  def inspect
    puts "Im monkeypatched!"
  end
end

When you then create a string and call inspect youll see that the method has been patched. 然后,当您创建一个字符串并调用inspect时,您将看到该方法已被修补。 Also you should be careful using monkeypatching because it can have some unwanted sideeffects, especally when you patch very basic classes like the String or Fixnum class. 另外你应该小心使用monkeypatching因为它可能有一些不必要的副作用,特别是当你修补非常基本的类,如String或Fixnum类。

Another option is to fork gem you are writing about, update it and keep in your repository and then refer to it in your Gemfile. 另一种选择是fork你正在编写的gem,更新它并保存在你的存储库中,然后在你的Gemfile中引用它。

Of course you may copy the whole source of this gem and put it in dedicated folder inside your app (lib/folder_for_your_gem) 当然你可以复制这个gem的整个来源并把它放在app里面的专用文件夹中(lib / folder_for_your_gem)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM