Class: PryRails::ShowModels

Inherits:
Pry::ClassCommand
  • Object
show all
Defined in:
lib/pry-rails/commands/show_models.rb

Instance Method Summary collapse

Instance Method Details

#colorize_matches(string) ⇒ Object



71
72
73
74
75
76
77
# File 'lib/pry-rails/commands/show_models.rb', line 71

def colorize_matches(string)
  if Pry.color
    string.to_s.gsub(grep_regex) { |s| "\e[7m#{s}\e[27m" }
  else
    string
  end
end

#display_activerecord_modelsObject



27
28
29
30
31
32
33
34
35
# File 'lib/pry-rails/commands/show_models.rb', line 27

def display_activerecord_models
  return unless defined?(ActiveRecord::Base)

  models = ActiveRecord::Base.descendants

  models.sort_by(&:to_s).each do |model|
    print_unless_filtered @formatter.format_active_record(model)
  end
end

#display_mongoid_modelsObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/pry-rails/commands/show_models.rb', line 37

def display_mongoid_models
  return unless defined?(Mongoid::Document)

  models = []

  ObjectSpace.each_object do |o|
    # If this is deprecated, calling any methods on it will emit a warning,
    # so just back away slowly.
    next if ActiveSupport::Deprecation::DeprecationProxy === o

    is_model = false

    begin
      is_model = o.class == Class && o.ancestors.include?(Mongoid::Document)
    rescue
      # If it's a weird object, it's not what we want anyway.
    end

    models << o if is_model
  end

  models.sort_by(&:to_s).each do |model|
    print_unless_filtered @formatter.format_mongoid(model)
  end
end

#grep_regexObject



79
80
81
# File 'lib/pry-rails/commands/show_models.rb', line 79

def grep_regex
  @grep_regex ||= Regexp.new(opts[:G], Regexp::IGNORECASE)
end

#options(opt) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'lib/pry-rails/commands/show_models.rb', line 8

def options(opt)
  opt.banner unindent <<-USAGE
    Usage: show-models

    show-models displays the current Rails app's models.
  USAGE

  opt.on :G, "grep", "Filter output by regular expression", :argument => true
end


63
64
65
66
67
68
69
# File 'lib/pry-rails/commands/show_models.rb', line 63

def print_unless_filtered(str)
  if opts.present?(:G)
    return unless str =~ grep_regex
    str = colorize_matches(str) # :(
  end
  output.puts str
end

#processObject



18
19
20
21
22
23
24
25
# File 'lib/pry-rails/commands/show_models.rb', line 18

def process
  Rails.application.eager_load!

  @formatter = PryRails::ModelFormatter.new

  display_activerecord_models
  display_mongoid_models
end