Skip to content

Instantly share code, notes, and snippets.

@WindyNova
Created June 7, 2024 20:58
Show Gist options
  • Select an option

  • Save WindyNova/6728aaf433a9fe81f9c5790cbdf43bd8 to your computer and use it in GitHub Desktop.

Select an option

Save WindyNova/6728aaf433a9fe81f9c5790cbdf43bd8 to your computer and use it in GitHub Desktop.
Meta Programming Example
class Profile
def self.field(name, type)
# Metaprogramming magic!
define_method(name) do
@attributes ||= {} # If @attributes doesn't exist, create it as an empty hash
@attributes[name]
end
define_method("#{name}=") do |value|
@attributes ||= {}
@attributes[name] = value
end
end
end
class UserProfile < Profile
field :name, :string
field :age, :integer
field :bio, :text
end
user = UserProfile.new
user.name = "Alice"
user.age = 30
user.bio = "Loves coding and cookies."
puts user.name # Output: Alice
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment