From: Ryan Davis Date: 2011-11-12T09:09:32+09:00 Subject: Re: referring to version numbers in a gem On Nov 11, 2011, at 14:04 , Chad Perrin wrote: > On Sat, Nov 12, 2011 at 05:28:15AM +0900, Chad Perrin wrote: >> How do I specify and access a gem's version number within the code of the >> gem itself? For example: >> >> 1. I write a library. >> 2. I write a command line utility that uses that library. >> 3. The utility uses OptionParser, with a --version option. >> 4. I package the things up inside a gem. >> >> What's the best way to specify the version number and give the code >> executed when the --version argument is supplied the ability to access >> that version number? > > For now, I'm going with the following. > > lib/gem_name.rb: > > module GemName > @version = Gem::Version.new 'N.N.N' Just use a plain string here. No reason to drag in Gem::Version at this point (rubygems is still pretty heavy). Also, a constant would be a better fit. > def self.version; @version; end There's no need for a class method here. Since the version string really is constant (for a given install), and there isn't any morphing you're going to do, stick with a const. > . . . > end > > gem_name.gemspec: > > load 'lib/gem_name.rb' > > Gem::Specification.new do |s| > s.version = GemName.version.to_s s.version = GemName::VERSION > . . . > end > > bin/gemname: > > . . . > > opts.on_tail('--version', help_text[:version]) do > puts "#{0} #{GemName.version} . . ." puts "#{0} #{GemName::VERSION} . . ." > end > end > > If anyone sees any problems with that approach, I'd like to hear about > it, but it seems to be working well enough for the moment. There's nothing _wrong_ with it, but it does do a bit more than it needs. Using a constant in the main class/module (I don't see the value in separating out the version to it's own file) and then referring to that everywhere is the DRYest way we could come up with when we were figuring this stuff out. It's the pattern that hoe uses and what sow spits out when you create a new project with it.