How can I write a hook that gets called when a RubyGem is installed?

萝らか妹 提交于 2019-12-22 08:07:01

问题


I'd like to write a Ruby snippet that gets run when my Gem is first installed via [sudo ]gem install mygem. Can it be done?


回答1:


It doesn't look like it's really supported. I found a "post_install_message" attribute that you should be able to set in the gem spec, but that won't execute code.

You may be able to do it by packaging your on-install code as an extension in your gem (as if it were a native extension), and providing a Rakefile to "build" the extension (i.e. call your code).




回答2:


I had the same problem. The best solution that I found is as follows:

# your_gem.gemspec
Gem::Specification.new do |spec|
  # ...
  spec.extensions = ['Rakefile']
end

-

# Rakefile
task :prepare do
  # Execute your post-installation code here
end

task default: :prepare



回答3:


You can try to do this using call of OS commands. I'll quote eample from irb but you can do same in your scripts too.

irb(main):001:0> system 'gem list | grep rails'
rails (2.1.1, 2.1.0)
=> true
irb(main):002:0> system 'gem list | grep railssssss'
=> false

You can use result of this command as the condition of your snippet execution.



来源:https://stackoverflow.com/questions/223151/how-can-i-write-a-hook-that-gets-called-when-a-rubygem-is-installed

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