0

I'm trying to adapt some existing code to also handle gems. This existing code needs the version number of the thing in question (here: the gem) and does some git stuff to get the relevant file (here I take the gemspec) in the right version, and then passes it on stdin to another script that extract the version number (and other stuff).

To avoid having to write code to parse a gemspec, I was trying to do:

spec = Gem::Specification::load('-')
puts spec.name
puts spec.version

But I can't make it read from stdin (it works fine if I hardcode a file name, but that won't work in my usecase). Can I do that, or is there another (easy) way to do it?

1 Answers1

0

Gem::Specification.load expects either a File instance or a path to a file as the first argument so the easiest way to solve this would be to simply create a Tempfile instance and write the data from stdin to it.

file = Tempfile.new
begin
  file.write(data_from_stdin) 
  file.rewind
  spec = Gem::Specification.load(file)
  puts spec.name
  puts spec.version
ensure
  file.close
  file.unlink
end
max
  • 96,212
  • 14
  • 104
  • 165
  • I'm not a ruby coder (just thought it made sense here - if I could get a full parse, it ould be easy to extend - but I'm close to just writing some perl to get the data I need), but that code just make ruby tell me that "data_from_stdin" is undefined. – Henrik supports the community Jun 25 '20 at 10:53
  • I thought it was pretty obvious that you need to provide the input as that variable. – max Jun 25 '20 at 10:56
  • Well, that became clear after trying it, but the thing is that I don't know how to access stdin, and feel like ruby is making that a lot harder than it needs to be. And putting it through a variable sounds like another indirection to waste time+code. – Henrik supports the community Jun 25 '20 at 11:53
  • https://stackoverflow.com/questions/273262/best-practices-with-stdin-in-ruby – max Jun 25 '20 at 12:10