Jay Fields describes a scenario for using dynamic method definition instead of method missing. Today i think i found a reason to use both method missing and dynamic method definition, for both speed and safety.
I have an ActiveRecord class that uses a serialized Hash as one of its parameters. There are about a dozen keys in that hash that are most frequently used, however there may be others. I want those most frequently used keys to be exposed as methods on the containing object like this:
class Query < ActiveRecord::Base
DYNAMIC_METHODS = [:my_key1, :my_key2, :my_other_key_exposed_as_method ]
serialize :params
def method_missing(methodname, *args)
if self.class.methods.include?(methodname)
super
elsif DYNAMIC_METHODS.include?(methodname.to_sym)
_build_dynamic_fields
self.send(methodname, *args)
else
super
end
end
# dynamically alias these methods to retrieve their results from the
# params object
def initialize(initparams=nil)
super
end
# called if a caller ever requests one of the dynamic methods above
def _build_dynamic_fields()
DYNAMIC_METHODS.each() do |m|
(class << Query;Query; end).class_eval do
define_method m do |*args|
return nil if params.nil?
self.send(’params’).send(’[]’, m.to_sym) rescue nil
end
end
end
end
Please indent your code. Learn how to use the PRE tag in your HTML pages (or if your blog software is not setup to accept tags within your post, set it up properly).