Creating an object using a string
class MyClass
def initialize
puts "An instance of MyClass has been created!"
end
end
class_name = "MyClass"
# Dynamically create a new object using the class specified by the string
new_object = Object.const_get(class_name).new
Turning into properties
class MyClass
attr_accessor :name, :age
def initialize
@name = nil
@age = nil
end
end
# Hash with property values
property_values = {
name: "John Doe",
age: 30
}
# Create a new object
my_object = MyClass.new
# Set properties using the hash
property_values.each do |key, value|
my_object.send("#{key}=", value)
end
# Print the object's properties
puts my_object.name
puts my_object.age
Load object from database by id
class_name = "YourModel"
id = 123
# Dynamically create an instance of the ActiveRecord model using the class specified by the string
model_object = Object.const_get(class_name).find(id)
JWT Authentication Notes