Skip to content

Instantly share code, notes, and snippets.

@delonnewman
Created June 18, 2020 21:49
Show Gist options
  • Save delonnewman/ae4cb8352c95a3de67c95e8167be600f to your computer and use it in GitHub Desktop.
Save delonnewman/ae4cb8352c95a3de67c95e8167be600f to your computer and use it in GitHub Desktop.
class Record < Hash
def self.has(key_name, opts = {})
opts = { type: opts } if Class === opts
schema[key_name] = opts
end
def self.schema
@schema ||= {}
end
def initialize(attrs = {})
merge!(attrs)
self.class.schema.each do |name, opts|
raise "#{name} is required" unless key?(name)
end
end
def to_s
"#{self.class}#{super}"
end
def slice(*keys)
self.class.new(super)
end
def merge(*hashes)
self.class.new(super)
end
def rename(mapping)
reduce({}) do |h, (key, value)|
k = mapping[key]
if k
h[k] = value
else
h[key] = value
end
h
end
end
def to_json
transform_keys do |key|
if key.to_s.include?('/')
key
else
"#{self.class.to_s.gsub('::', '.').downcase}/#{key}"
end
end.to_json
end
# these can only be used internally
private def []=(key, value)
super
end
private def store(key, value)
super
end
private def merge!(*hashes)
super
end
# disable all mutable methods
def clear
raise 'not implemented call to_h to treat as a native hash'
end
def compact!
raise 'not implemented call to_h to treat as a native hash'
end
def default=(value)
raise 'not implemented call to_h to treat as a native hash'
end
def default_proc
raise 'not implemented call to_h to treat as a native hash'
end
def default_proc=(proc_obj)
raise 'not implemented call to_h to treat as a native hash'
end
def delete(key)
raise 'not implemented call to_h to treat as a native hash'
end
def delete_if
raise 'not implemented call to_h to treat as a native hash'
end
def keep_if
raise 'not implemented call to_h to treat as a native hash'
end
def filter!
raise 'not implemented call to_h to treat as a native hash'
end
def reject!
raise 'not implemented call to_h to treat as a native hash'
end
def rehash
raise 'not implemented call to_h to treat as a native hash'
end
def select!
raise 'not implemented call to_h to treat as a native hash'
end
def replace(hash)
raise 'not implemented call to_h to treat as a native hash'
end
def shift
raise 'not implemented call to_h to treat as a native hash'
end
def transform_keys!
raise 'not implemented call to_h to treat as a native hash'
end
def transform_values!
raise 'not implemented call to_h to treat as a native hash'
end
def update(*hashes)
raise 'not implemented call to_h to treat as a native hash'
end
end
module Test
class Person < Record
has :name, String
has :dob, Date
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment