Home How to store "macros" in rails console?
Reply: 3

How to store "macros" in rails console?

sakurashinken
1#
sakurashinken Published in 2018-01-12 20:05:30Z

This question already has an answer here:

  • How to create a custom method for the rails console? 2 answers

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.

teju c
2#
teju c Reply to 2018-01-12 21:33:25Z

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

Josh Brody
3#
Josh Brody Reply to 2018-01-12 20:21:54Z

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.

Tamer Shlash
4#
Tamer Shlash Reply to 2018-01-12 20:25:53Z

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
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.321778 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO