1

I have a multi-tenant rails app that uses the apartment gem. When I use rails console, I am constantly calling Apartment::Tenant.switch to navigate between apartments. I would like to create a config file somewhere that where I can abreviate this call to something shorter to type. How would I go about doing this so that when I start up the console with rails console this shorter call is available? I was imagining something like

swtich = Apartment::Tenant.switch

And then whenever I call switch then it calls the original function.

sakurashinken
  • 3,940
  • 8
  • 34
  • 67

3 Answers3

1

well. not actually macros but we have dynamic_method define right.

so u can do this in your rails console:

define_method :bar do
  Apartment::Tenant.switch
end

and then you can call bar method as short for your method.

To add it in initializers i have created one file say bar.rb in initializers folder.

then I have done it , I don't if its ideal:

class Object
    def bar
        Apartment::Tenant.switch
    end
end

restart you console and call bar

teju c
  • 336
  • 2
  • 8
1

I don't really like global variables, but you can place this in an initalizers file:

$switch = (Class.new do
  def [](tenant, &block)
    Apartment::Tenant.switch(tenant, &block)
  end
end).new

and then use it like this:

$switch['tenant_name'] do
  ....
end
Tamer Shlash
  • 9,314
  • 5
  • 44
  • 82
0

There has to be a better way of doing this and I don't recommend this whatsoever. Drop this into an initializer or application.rb or similar.

module Kernel
  def switch
    Apartment::Tenant.switch
  end
end

will allow you to simply call switch in your console. You'll probably break some other stuff though, and you should take steps to ensure that this is only accessible via the console.

Josh Brody
  • 5,153
  • 1
  • 14
  • 25