Created
January 9, 2025 16:41
-
-
Save havenwood/e6e5f8fdbe797ee7a71f00bac3a936c8 to your computer and use it in GitHub Desktop.
A `~{meaning: 42}`-style Data literal implemented in Ruby
This file contains 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
module DataLiteral | |
refine Hash do | |
def to_data(name = nil) | |
if name | |
unless Object.const_defined?(name) | |
Object.const_set(name, Data.define(*keys)) | |
end | |
Object.const_get(name).new(*values) | |
else | |
Data.define(*keys).new(*values) | |
end | |
end | |
alias ~@ to_data | |
end | |
end | |
using DataLiteral | |
~{aim: true, tip: :broadhead} | |
#=> #<data aim=true, tip=:broadhead> | |
{aim: true, tip: :broadhead}.to_data(:Arrow) | |
#=> #<data Arrow aim=true, tip=:broadhead> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment