The Magic of Ruby: Harnessing method_missing for Dynamic Proxies
If you're coming from Java or C++, Ruby's flexibility feels like cheating. In 2006, we're seeing more developers embrace the "duck typing" philosophy. One of the most powerful tools in a Rubyist's belt is the method_missing hook. This allows an object to handle calls to methods that aren't explicitly defined.
The Ghost Method Pattern
Imagine you want to create a simple wrapper around a Hash that allows you to access keys as if they were methods. This is a classic use case for method_missing.
class OpenStructLite
def initialize(hash = {})
@data = hash
end
def method_missing(name, *args, &block)
# Check if the name ends with an equals sign for assignment
if name.to_s =~ /=\z/
key = name.to_s.sub('=', '').to_sym
@data[key] = args.first
elsif @data.has_key?(name)
@data[name]
else
# Always call super to maintain default behavior (NoMethodError)
super
end
end
def respond_to?(name, include_private = false)
@data.has_key?(name) || name.to_s =~ /=\z/ || super
end
end
user = OpenStructLite.new(name: "Matz")
puts user.name # => "Matz"
user.location = "Japan"
puts user.location # => "Japan"
Building a Logger Proxy
Another great use for this is creating a proxy that logs every method call to an object before delegating it. This is a form of Aspect-Oriented Programming (AOP) that is trivial in Ruby 1.8.
class LoggingProxy
def initialize(target)
@target = target
end
def method_missing(name, *args, &block)
puts "DEBUG: Calling method '#{name}' on #{@target.inspect} with #{args.inspect}"
@target.send(name, *args, &block)
end
end
array = LoggingProxy.new([1, 2, 3])
array.push(4)
# Output: DEBUG: Calling method 'push' on [1, 2, 3] with [4]
Performance Considerations
While method_missing is incredibly powerful, it comes with a performance hit. Each time a "ghost method" is called, Ruby has to search the entire method lookup chain before finally hitting method_missing. In high-performance loops, consider using define_method to dynamically create the method after the first time it's called, effectively "caching" the logic.
Aunimeda develops websites and web applications for businesses - corporate sites, e-commerce, portals, and custom platforms.
Contact us to discuss your web project. See also: Web Development, E-commerce Development