Create Classes At Runtime
Join the DZone community and get the full member experience.
Join For FreeDr Nic's Magic Models adds automatic ActiveRecord generation if you haven't defined a model, and for all ActiveRecords it can generate associations and validations on-the-fly based on the database schema (the table and column definitions).
It does this with some interesting Ruby meta-programming.
For example, if you want to create a new class at runtime, and assign it a superclass, try the following:
def create_class(class_name, superclass, &block)
klass = Class.new superclass, &block
Object.const_set class_name, klass
end
With this code, you can create a class as follows:
create_class('Person', ActiveRecord::Base) do
set_table_name :people
def fullname
"#{firstname} #{lastname}" # assuming the people table has firstname,lastname columns
end
end
Opinions expressed by DZone contributors are their own.
Trending
-
The Role of AI and Programming in the Gaming Industry: A Look Beyond the Tables
-
How To Scan and Validate Image Uploads in Java
-
Exploring the Capabilities of eBPF
-
Designing a New Framework for Ephemeral Resources
Comments