问题
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