1d61786256cde4ad5a3afb2f1ff3812b

I am migrating some code to ruby 1.9 and was wondering if you have any better idea how to run specific code based on the ruby version?

unless exceptions.is_a?( Array ) 
  if RUBY_VERSION[0, 2] == "1.8"
    exceptions = exceptions.to_s.to_a
  else
    exceptions = exceptions.to_s.lines.to_a
  end
end
# both "text" and :text should be converted into ["text"]

Refactorings

No refactoring yet !

E8f0d6e9bc8bca695b3c5bdf75cdcc03

Martin Plöger

August 25, 2009, August 25, 2009 07:38, permalink

1 rating. Login to rate!
def is_18?
  RUBY_VERSION =~ /1.8/
end

# _if_ in Ruby is functional, so you can put the assignment in front of it

unless exceptions.is_a? Array
  exceptions = if is_18?
    exceptions.to_s.to_a
  else
    exceptions.to_s.lines.to_a
  end
end

#Or maybe with a block that is called when the version matches. Otherwise _self_ is returned so you can chain it easily.

def when_18 &block
  is_18? ? instance_eval &block : self
end

unless exceptions.is_a? Array
  exceptions = exceptions.to_s.when_18 { lines }.to_a
end
C1f7bc8064161e7408ef62d97bb636ac

Mort

August 25, 2009, August 25, 2009 13:45, permalink

1 rating. Login to rate!

I'd advise creating two branches of your project for the two different versions. Maintaining readable code with this kind of version checking looks to be a good way to drive oneself mad...

Above refactoring needs a regex fix, see below.

def is_18?
  RUBY_VERSION =~ /^1\.8/
end
1d61786256cde4ad5a3afb2f1ff3812b

Billskog

August 25, 2009, August 25, 2009 16:57, permalink

No rating. Login to rate!

I see what you mean when you say it could be they way to masness. But i am afraid a version branch is unlikely for this project, so for now I will go with the following solution. Thanks for the warning tho.

unless exceptions.is_a?( Array ) 
  exceptions = RUBY_VERSION =~ /^1\.8/ ? exceptions.to_s.to_a : exceptions = exceptions.to_s.lines.to_a
end
A8d3f35baafdaea851914b17dae9e1fc

Adam

August 25, 2009, August 25, 2009 21:10, permalink

1 rating. Login to rate!
class String
  unless defined?(lines)
    def lines
      self
    end
  end
end

unless exceptions.is_a?( Array ) 
  exceptions = exceptions.to_s.lines.to_a
end
7f00244a6387413b37ee449f234ec045

Marc-Andre

September 1, 2009, September 01, 2009 18:43, permalink

No rating. Login to rate!

Shameless plug for my backports gem (http://github.com/marcandre/backports ). Note that String#lines was added in 1.8.7 (not in 1.9)

require 'backports'

exceptions = exceptions.to_s.lines.to_a

Your refactoring





Format Copy from initial code

or Cancel