Module: Gemika::Env

Extended by:
Env
Included in:
Env
Defined in:
lib/gemika/env.rb

Overview

Version switches to write code that works with different versions of Ruby and gem dependencies.

Constant Summary collapse

VERSION_PATTERN =
/(?:\d+\.)*\d+/

Instance Method Summary collapse

Instance Method Details

#gem?(*args) ⇒ Boolean

Check if the given gem was activated by the current gemfile. It might or might not have been required yet.

Examples:

Gemika::Env.gem?('activerecord')
Gemika::Env.gem?('activerecord', '= 5.0.0')
Gemika::Env.gem?('activerecord', '~> 4.2.0')

Returns:

  • (Boolean)


64
65
66
67
68
69
70
71
72
# File 'lib/gemika/env.rb', line 64

def gem?(*args)
  options = args.last.is_a?(Hash) ? args.pop : {}
  name, requirement_string = args
  if options[:gemfile] && !process_gemfile?(options[:gemfile])
    gem_in_gemfile?(options[:gemfile], name, requirement_string)
  else
    gem_activated?(name, requirement_string)
  end
end

#gemfileObject

Returns the path to the gemfile for the current Ruby process.



16
17
18
19
20
21
22
# File 'lib/gemika/env.rb', line 16

def gemfile
  if @gemfile_changed
    @process_gemfile
  else
    ENV['BUNDLE_GEMFILE']
  end
end

#github?Boolean

Return whether this process is running within a Github Actions build.

Returns:

  • (Boolean)


100
101
102
# File 'lib/gemika/env.rb', line 100

def github?
  ENV.key?('GITHUB_WORKFLOW')
end

#rubyObject

Returns the current version of Ruby.



77
78
79
# File 'lib/gemika/env.rb', line 77

def ruby
  RUBY_VERSION
end

#ruby?(requirement) ⇒ Boolean

Check if the current version of Ruby satisfies the given requirements.

Examples:

Gemika::Env.ruby?('>= 2.1.0')

Returns:

  • (Boolean)


87
88
89
# File 'lib/gemika/env.rb', line 87

def ruby?(requirement)
  requirement_satisfied?(requirement, ruby)
end

#travis?Boolean

Returns whether this process is running within a TravisCI build.

Returns:

  • (Boolean)


94
95
96
# File 'lib/gemika/env.rb', line 94

def travis?
  !!ENV['TRAVIS']
end

#with_gemfile(path, *args, &block) ⇒ Object

Changes the gemfile to the given path, runs the given block, then resets the gemfile to its original path.

Examples:

Gemika::Env.with_gemfile('gemfiles/Gemfile.rails3') do
  system('rspec spec') or raise 'RSpec failed'
end


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/gemika/env.rb', line 33

def with_gemfile(path, *args, &block)
  # Make sure that if block calls  #gemfile we still return the gemfile for this
  # process, regardless of what's in ENV temporarily
  @gemfile_changed = true
  @process_gemfile = ENV['BUNDLE_GEMFILE']

  # .with_clean_env is deprecated since Bundler ~> 2.
  bundler_method = if Gemika::Env.gem?('bundler', '< 2')
    :with_clean_env
  else
    :with_unbundled_env
  end

  Bundler.send(bundler_method) do
    ENV['BUNDLE_GEMFILE'] = path
    block.call(*args)
  end
ensure
  @gemfile_changed = false
  ENV['BUNDLE_GEMFILE'] = @process_gemfile
end