Module: RailsConsoleToolkit::Helpers

Defined in:
lib/rails_console_toolkit/helpers.rb

Instance Method Summary collapse

Instance Method Details

#alias_helper(new_name, old_name) ⇒ Object



47
48
49
# File 'lib/rails_console_toolkit/helpers.rb', line 47

def alias_helper(new_name, old_name)
  helper(new_name) { |*args, &block| send(old_name, *args, &block) }
end

#helper(name, &block) ⇒ Object



18
19
20
# File 'lib/rails_console_toolkit/helpers.rb', line 18

def helper(name, &block)
  helper_methods[name.to_sym] = block
end

#install!(target_module = Rails::ConsoleMethods) ⇒ Object



12
13
14
15
16
# File 'lib/rails_console_toolkit/helpers.rb', line 12

def install!(target_module = Rails::ConsoleMethods)
  helper_methods.each do |name, block|
    target_module.define_method(name, &block)
  end
end

#model_helper(klass_name, as: nil, by: nil, cached: true) ⇒ Object



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/rails_console_toolkit/helpers.rb', line 22

def model_helper(klass_name, as: nil, by: nil, cached: true)
  unless String === klass_name
    raise TypeError, "The class name is expected to be a String, got #{klass_name.inspect} (#{klass_name.class}) instead."
  end

  method_name = as || klass_name.gsub('::', '_').underscore
  attribute_names = by || []

  record = nil # use the closure as a cache

  helper method_name do |key = nil|
    klass = klass_name.constantize
    record = nil unless cached

    if key
      record = nil
      record = key if klass === key
      record ||= klass.find(key) if Numeric === key
      attribute_names.find { |name| record ||= klass.find_by(name => key) }
    end

    record
  end
end

#remove_helper(name) ⇒ Object



51
52
53
# File 'lib/rails_console_toolkit/helpers.rb', line 51

def remove_helper(name)
  helper_methods.delete(name.to_sym)
end

#use_pack(pack_name) ⇒ Object



4
5
6
7
8
9
10
# File 'lib/rails_console_toolkit/helpers.rb', line 4

def use_pack pack_name
  unless %w[aliases solidus utils].include? pack_name.to_s
    raise Error, "unknown pack name: #{pack_name}"
  end

  require "rails_console_toolkit/#{pack_name}"
end