Search code examples
ruby-on-railsmulti-tenantapartment-gem

How select specific tenant after enter on console?


The code below, stored at config/initializers/console.rb works only at first time I exec rails console CLI. When exit and enter again, no selection message is displayed, but the preview tenant selected is loaded.

if defined?(Rails::Console) || $PROGRAM_NAME.include?('spring')
  tenants = Apartment.tenant_names.sort
  default = tenants.first

  puts "Available tenants: #{tenants.join(', ')}"

  print "Select tenant (#{default}): "
  tenant = gets.strip

  Apartment::Tenant.switch! tenants.include?(tenant) ? tenant : default
end

I wish every time when enter at rails console ask for what tenant will be loaded.

Thanks!


Solution

  • The only way I could get Apartment::Tenant.switch! to work in the Rails console was by creating the following .irbrc file in the project's root directory:

    IRB.conf[:IRB_RC] = Proc.new do
      tenants = Apartment.tenant_names.sort
      puts "Available tenants: #{tenants.join(', ')}"
    
      print "Select tenant: "
      tenant = gets.strip
    
      unless tenant.empty?
        if tenants.include?(tenant)
          Apartment::Tenant.switch!(tenant)
        else
          puts "Tenant not found in list '#{tenant}'"
        end
      end
      puts "Tenant set to '#{Apartment::Tenant.current}'"
    end