Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add a class to a module in Ruby

Let's say I create a module dynamically like so:

app = Object.const_set('CoolModule', Module.new)

Is there anyway to add a class to that module? Something like this maybe?

app << (class Application; end)

I'm basically trying to get the following going

module 'CoolModule'.turnThisIntoAModule
  class Application < Rails::Application
    config.blabla = 2
  end
end
like image 283
Ingo Avatar asked Mar 29 '16 15:03

Ingo


2 Answers

You may add a class for dynamically named module like in the following example:

app = Object.const_set('CoolModule', Module.new)

Object.const_get('CoolModule').
  const_set('Application', Class.new(Rails::Application) do
    config.blabla = 2
  end)

If you have access to app object at point of call, it may replace Object.const_get('CoolModule') expression, of course.

Module.module_eval suggests itself but it unfortunately does not do scoped lookup in its block form. It does it in the string argument form, but I'd discourage use of evals on strings.

like image 57
joanbm Avatar answered Oct 20 '22 13:10

joanbm


You just repeat the same thing.

CoolModule.const_set("SomeVeryDynamicName", Module.new do
  class Application < Rails::Application
    config.blabla = 2
  end
end)
like image 2
sawa Avatar answered Oct 20 '22 13:10

sawa