Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Dependency in Ruby Gemspec

Tags:

ruby

rubygems

I'm building a gem that needs a json gem installed in order for it to work. It doesn't matter which json gem: json_pure, json-jruby, or the C-based json.

Is there a good way of defining this in a gemspec? This response suggests maintaining a completely separate gem for each version, but it seems like there has got to be a better way.

Does anybody have any experience with this?

Should I just use the spec.requirements option to give the user a notice that he/she needs a json gem?

like image 211
Jimmy Z Avatar asked Dec 02 '09 21:12

Jimmy Z


1 Answers

Yes, I would suggest a simple text requirement in spec.requirements. I would also recommend some sort of load-chaining when the gem first loads:

# in init.rb and/or rails/init.rb:
unless Object.const_defined?(:JSON)
  begin
    require 'json_pure'
  rescue LoadError
    begin
      require 'json-ruby'
    rescue LoadError
      require 'json'
    end
  end
end
unless Object.const_defined?(:JSON)
  raise "Could not load gem MyGem; did you install one of json_pur, json-ruby, or the C-based json library?"
end
like image 104
James A. Rosen Avatar answered Oct 06 '22 21:10

James A. Rosen