Module: Carbonado

Extended by:
Carbonado
Included in:
Carbonado
Defined in:
lib/carbonado.rb,
lib/carbonado/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Instance Method Details

#activate_gem(gem_name, version = nil, requirer = nil) ⇒ Object

Activate the named gem. Specify a version requirement as a string or a Gem::Requirement object. This will also recursively activate the dependencies of the gem. It can fail if a gem has a dependency that is already activated which doesn’t satisfy the requirements of the given gem or one of its dependencies. Otherwise it can fail if the given gem or one of its dependencies is not installed

Raises:



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/carbonado.rb', line 11

def activate_gem(gem_name, version = nil, requirer = nil)
  version_requirement = version.is_a?(Gem::Requirement) ? version : Gem::Requirement.default
  loaded_gem = Gem::Specification.stubs.select{ |s| s.name == gem_name }.first
  if !loaded_gem.nil?
    return true if Gem::Requirement.new(version_requirement).satisfied_by?(loaded_gem.version)      

    error_msg = "There is alread an activated version of #{gem_name}"
    error_msg += ", required by #{requirer}" if requirer
    error_msg += ", that does not meet the version requirement #{version_requirement}"
    raise Error, error_msg
  end
  installed_versions = installed_stubs.select{ |s| s.name == gem_name }.sort_by(&:version)
  raise Error, "Could not find #{gem_name} in list of installed gems" if installed_versions.empty?
  allowed_versions = installed_versions.select do |s|
    Gem::Requirement.new(version_requirement).satisfied_by?(s.version)
  end

  selected_spec = allowed_versions.last.to_spec
  selected_spec.dependencies.select(&:runtime?).each{ |dep| activate_gem(dep.name) }    
  selected_spec.activate
end

#stub_gem_methodObject

This method stubs the Kernel#gem method to make it a noop for the code executed in the yielded block. This method is useful if there is a gem that uses the Kernel#gem method to activate a gem from the bundle that you have already activated using the activate_gem method above. One example is the ActiveRecord::Base.establish_connection method. Depending on the adapter, this will try to activate the appropriate gem using the ‘gem’ method, which will fail because our approach doesn’t alter the bundle. I guess this is a TODO, since it may be possible to update the bundle so that the gem method will succeed which would be a better solution.



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/carbonado.rb', line 40

def stub_gem_method
  Kernel.define_method :fake_gem do |*args|
  end

  Kernel.alias_method :real_gem, :gem
  Kernel.alias_method :gem, :fake_gem

  yield

  Kernel.alias_method :gem, :real_gem
end