There is a pattern that keeps coming up in my ruby code and I'm somewhat ambivalent about it. It's somewhere between a Hash and a Struct. Basically I used method_missing to return/set values in the Hash unless I want to override a specific value with some logic or flatten out the complex underlying structure in the JSON. It's very flexible and quickly allows code changes, but it also hides much of the structure of the object.
In effect, the structure is in the data ( JSON file ) and not in the code. Is this an effective Pattern or just asking for trouble down the road?
class AttributeKeeper
def initialize
@attributes = Hash.new
end
def import
// Special import methods usually from JSON
end
def export
// Export to JSON with maybe some data verification along the way.
end
def special_value= (value )
// Perform data check on special value
@attributes[special_value] = value
end
def checked_value
// Return value if passes checks.
end
def method_missing(meth, *args, &block)
smeth = meth.to_s
trim = smeth.chomp('=') #Handle setter methods.
unless ( smeth == trim )
@attributes[trim] = args[0]
else
@attributes[smeth]
end
end
def responds_to?(meth)
smeth = meth.to_s
if( @attributes[smeth] or smeth[-1,1] == '=')
true
else
super
end
end
end