Skip to content

Instantly share code, notes, and snippets.

@jschairb
Created July 8, 2014 15:25
Show Gist options
  • Save jschairb/69598fa2ac8b61a6d55a to your computer and use it in GitHub Desktop.
Save jschairb/69598fa2ac8b61a6d55a to your computer and use it in GitHub Desktop.
Dual-access of objects that replace primitive data structure
require 'logger'
module PrimitiveAccess
def self.included(base)
base.send(:include, InstanceMethods)
end
module InstanceMethods
def primitive_logger
@logger ||= Logger.new(STDOUT)
end
def []=(key, value)
primitive_logger.warn "Hash-based setter of object for key: #{key}"
send("#{key}=", value)
end
def [](key)
primitive_logger.warn "Hash-based getter of object for key: #{key}"
send("#{key}")
end
end
end
class Future
include PrimitiveAccess
attr_accessor :foo, :blah
def initialize(attributes)
attributes.each { |k,v| send("#{k}=", v) }
end
end
primitive = { foo: 'bar', blah: 'bah' }
future = Future.new(primitive)
puts future.foo # => 'bar'
puts future[:foo] # => 'bar'
future.foo = 'yah'
puts future.foo # => 'yah'
puts future[:foo] # => 'yah'
future[:foo] = 'nah'
puts future.foo # => 'nah'
puts future[:foo] # => 'nah'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment