Created
          July 8, 2014 15:25 
        
      - 
      
- 
        Save jschairb/69598fa2ac8b61a6d55a to your computer and use it in GitHub Desktop. 
    Dual-access of objects that replace primitive data structure
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | 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