Created
June 7, 2024 20:58
-
-
Save WindyNova/6728aaf433a9fe81f9c5790cbdf43bd8 to your computer and use it in GitHub Desktop.
Meta Programming Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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