Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created January 9, 2025 16:41
Show Gist options
  • Save havenwood/e6e5f8fdbe797ee7a71f00bac3a936c8 to your computer and use it in GitHub Desktop.
Save havenwood/e6e5f8fdbe797ee7a71f00bac3a936c8 to your computer and use it in GitHub Desktop.
A `~{meaning: 42}`-style Data literal implemented in Ruby
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