Module: GemToolbox::CommonOptions

Overview

This module was ripped from open_gem

Instance Method Summary collapse

Instance Method Details

#add_command_option(description = nil) ⇒ Object



7
8
9
# File 'lib/gem_toolbox/common_options.rb', line 7

def add_command_option(description=nil)
  add_option('-c', '--command COMMAND', description || 'Execute command at path of the gem') { |value,options| options[:command] = value }
end

#add_exact_match_optionObject



15
16
17
# File 'lib/gem_toolbox/common_options.rb', line 15

def add_exact_match_option
  add_option('-x', '--exact', 'Only list exact matches') { |value,options| options[:exact] = true }
end

#add_latest_version_optionObject



11
12
13
# File 'lib/gem_toolbox/common_options.rb', line 11

def add_latest_version_option
  add_option('-l', '--latest', 'If there are multiple versions, use the latest') { |value,options| options[:latest] = true }
end

#get_path(name) ⇒ Object



47
48
49
50
51
# File 'lib/gem_toolbox/common_options.rb', line 47

def get_path(name)
  if spec = get_spec(name)
    spec.full_gem_path
  end
end

#get_spec(name) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/gem_toolbox/common_options.rb', line 19

def get_spec(name)
  dep = Gem::Dependency.new(name, options[:version])
  specs = Gem.source_index.search(dep)
  if block_given?
    specs = specs.select{|spec| yield spec}
  end

  if specs.length == 0
    # If we have not tried to do a pattern match yet, fall back on it.
    if(!options[:exact] && !name.is_a?(Regexp))
      pattern = /#{Regexp.escape name}/
      get_spec(pattern)
    else
      say "#{name.inspect} is not available"
      return nil
    end

  elsif specs.length == 1 || options[:latest]
    return specs.last

  else
    choices = specs.map{|s|"#{s.name} #{s.version}"}
    c,i = choose_from_list "Open which gem?", choices
    return specs[i] if i

  end
end

#show(file) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/gem_toolbox/common_options.rb', line 53

def show(file)
  pager = options[:command] || ENV['GEM_PAGER'] || ENV['PAGER']

  if !pager
    say "Either set $GEM_PAGER, $PAGER, or use -c <command_name>"
  else
    command_parts = Shellwords.shellwords(pager)
    command_parts << file
    success = system(*command_parts)
    if !success 
      raise Gem::CommandLineError, "Could not run '#{pager} #{file}', exit code: #{$?.exitstatus}"
    end
  end    

end