Class: HashPipe

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/hashpipe.rb

Overview

rbx has it.

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args) ⇒ Object



69
70
71
72
73
74
75
76
77
# File 'lib/hashpipe.rb', line 69

def method_missing(sym, *args)
  newsym = sym.to_s.gsub(/=$/, '').to_sym
  if __respond_to?(newsym)
    raise ArgumentError, "#{newsym} cannot be defined on #{self.inspect}"
  else
    self.__class__.create_accessor(newsym, self) 
    self.__send__(sym, *args)
  end
end

Class Method Details

.callable_ivar(ivar) ⇒ Object



39
40
41
# File 'lib/hashpipe.rb', line 39

def self.callable_ivar(ivar)
  ivar[/^@?(.*)$/, 1].to_sym
end

.create_accessor(sym, obj) ⇒ Object



32
33
34
35
36
# File 'lib/hashpipe.rb', line 32

def self.create_accessor(sym, obj)
  unless obj.__respond_to?(sym)
    class << obj; self; end.attr_accessor(sym)
  end
end

Instance Method Details

#[](sym_or_str) ⇒ Object



59
60
61
62
# File 'lib/hashpipe.rb', line 59

def [](sym_or_str)
  self.__class__.create_accessor(sym_or_str, self) if self.__respond_to?(:method_missing)
  self.__send__(sym_or_str)
end

#[]=(sym_or_str, value) ⇒ Object



64
65
66
67
# File 'lib/hashpipe.rb', line 64

def []=(sym_or_str, value)
  self.__class__.create_accessor(sym_or_str, self) if self.__respond_to?(:method_missing)
  self.__send__(:"#{sym_or_str}=", value)
end

#eachObject



89
90
91
92
93
94
# File 'lib/hashpipe.rb', line 89

def each
  __instance_variables__.each do |ivar|
    callable = self.__class__.callable_ivar(ivar)
    yield(callable, self.__send__(callable))
  end
end

#keysObject



79
80
81
# File 'lib/hashpipe.rb', line 79

def keys
  __instance_variables__.map { |ivar| self.__class__.callable_ivar(ivar) } 
end

#lock!Object



96
97
98
99
100
# File 'lib/hashpipe.rb', line 96

def lock!
  if __respond_to?(:method_missing)
    class << self; undef_method :method_missing; end
  end
end

#valuesObject



83
84
85
86
87
# File 'lib/hashpipe.rb', line 83

def values
  __instance_variables__.map { |ivar|
    self.__send__(self.__class__.callable_ivar(ivar))
  }
end