Skip to content

Instantly share code, notes, and snippets.

@rainerborene
Created November 16, 2017 18:08
Show Gist options
  • Save rainerborene/f2a15275894fd481bb7e34e77b07a72c to your computer and use it in GitHub Desktop.
Save rainerborene/f2a15275894fd481bb7e34e77b07a72c to your computer and use it in GitHub Desktop.
module KeyMapping
def self.included(base)
base.instance_variable_set(:@key_mappings, {})
base.extend(ClassMethods)
base.send(:include, InstanceMethods)
end
module ClassMethods
attr_reader :key_mappings
def inherited(klass)
super
klass.instance_variable_set(:@key_mappings, key_mappings.dup)
end
def key(props)
path, name = props.to_a.first
name = path if name.nil?
key_mappings[name] = path.split('.').map do |value|
value.match(/^(\d+)$/) ? $1.to_i : value.to_sym
end
end
end
module InstanceMethods
def initialize(hash = {})
self.class.key_mappings.each do |key, path|
self[key] = hash.dig(*path)
end
end
end
end
class Resource < Hash
include KeyMapping
end
class Video < Resource
key 'details.id' => :id
end
z = Video.new details: { id: 'blah' }
puts z[:id]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment