Module: PaperTrail::Rails::General

Defined in:
lib/paper_trail/rails/general.rb

Class Method Summary collapse

Class Method Details

.select_user(filter: :itself, other_allowed_values: [], prompt: '"Please enter the index of one of the users above, or a valid User id', required: true) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/paper_trail/rails/general.rb', line 7

def select_user(filter: :itself, other_allowed_values: [], prompt: '"Please enter the index of one of the users above, or a valid User id', required: true)
  config = PaperTrail::Rails.config

  user_options = nil
  User.logger.silence do
    puts 'index. user'
    user_options = filter.to_proc.(User.all)
    user_options.each.with_index do |user, i|
      puts "%2s. %s" % [i + 1, user.inspect]
    end
  end

  user = nil
  until user.present? do
    print "#{prompt}: "
    input = gets.chomp
    case input
    when *other_allowed_values
      user = input
    else
      if (i = Integer(input) rescue nil)
        user = user_options[i - 1] || (User.find(input) rescue nil)
      else  # allow for non-numeric ids like uuids
        user =                         User.find(input) rescue nil
      end
    end
    break unless required
  end
  user
end