如何编写安装RubyGem时调用的钩子?

时间:2022-04-19 02:11:52

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?

我想写一个Ruby代码片段,当我的Gem首次通过[sudo] gem install mygem安装时运行。可以吗?

3 个解决方案

#1


2  

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.

它看起来并不像它真的支持。我找到了一个“post_install_message”属性,您应该能够在gem规范中设置该属性,但这不会执行代码。

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).

您可以通过将安装后的代码打包为gem中的扩展(就好像它是本机扩展)来实现它,并提供Rakefile来“构建”扩展(即调用您的代码)。

#2


1  

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


-2  

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.

您可以尝试使用OS命令调用来执行此操作。我将引用irb的例子,但你也可以在你的脚本中做同样的事情。

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.

您可以使用此命令的结果作为代码段执行的条件。

#1


2  

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.

它看起来并不像它真的支持。我找到了一个“post_install_message”属性,您应该能够在gem规范中设置该属性,但这不会执行代码。

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).

您可以通过将安装后的代码打包为gem中的扩展(就好像它是本机扩展)来实现它,并提供Rakefile来“构建”扩展(即调用您的代码)。

#2


1  

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


-2  

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.

您可以尝试使用OS命令调用来执行此操作。我将引用irb的例子,但你也可以在你的脚本中做同样的事情。

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.

您可以使用此命令的结果作为代码段执行的条件。