Created
November 16, 2017 18:08
-
-
Save rainerborene/f2a15275894fd481bb7e34e77b07a72c to your computer and use it in GitHub Desktop.
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 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