Dynamic Class Definition with a Class Name

Dynamic Class Definition WITH a Class Name

The name of a class is simply the name of the first constant that refers to it.

I.e. if I do myclass = Class.new and then MyClass = myclass, the name of the class will become MyClass. However I can't do MyClass = if I don't know the name of the class until runtime.

So instead you can use Module#const_set, which dynamically sets the value of a const. Example:

dynamic_name = "ClassName"
Object.const_set(dynamic_name, Class.new { def method1() 42 end })
ClassName.new.method1 #=> 42

How to pass Dynamic class name inside of the Class.forName()?

I fix error using trim method to remove the unwanted space and got working like charm .

ES6 Dynamic class names

There is probably a better solution for whatever you are trying to achieve, but you can assign a class expression to an object:

let classes = {};
classes[someName] = class { ... };

This didn't really change in ES2015: if you want to create a dynamically named binding, you have to use an object or some other mapping instead.

How to create dynamic class names for ul?

this is the most simple way to achive what you want

var ul = document.querySelectorAll(".main-nav ul")
ul.forEach((each,i)=>{
each.classList.add("ul-"+i)
})

Creating dynamic class from a string containing the class definition

You can use the CSharpCodeProvider to compile your result at runtime and then use the Activator - Class to create an object from your generated code.

// compile your piece of code to dll file
Microsoft.CSharp.CSharpCodeProvider cSharpCodeProvider = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters compilerParameters = new System.CodeDom.Compiler.CompilerParameters();
compilerParameters.GenerateInMemory = true;
compilerParameters.GenerateExecutable = false;
System.CodeDom.Compiler.CompilerResults cResult = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, "using System; namespace Tables { 'put here your class definition' }");

// then load your dll file, get type and object from class
Assembly assembly = cResult.CompiledAssembly;
Type myTableType = assembly.GetType("Tables.Tablename");
var finalResult = Activator.CreateInstance(myTableType);

Rails: dynamically define class method based on parent class name within module/concern

You can't do it like that - at this point it is not yet known which class (or classes) are including the module.

If you define a self.included method it will be called each time the module is included and the thing doing the including will be passed as an argument. Alternatively since you are using AS::Concern you can do

included do 
#code here is executed in the context of the including class
end


Related Topics



Leave a reply



Submit