HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Ruby Dynamic Struct - Pattern or AntiPattern?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
antipatternstructrubydynamicpattern

Problem

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

Solution

I have the feeling that your patterns is very similar to the idea behind OpenStruct and similar libraries, such as Hashie::Mash.

So I would say, it's definitely not an anti-pattern in some cases. Such structures are very helpful when parsing and converting structured inputs, for example an API call.

Context

StackExchange Code Review Q#37542, answer score: 3

Revisions (0)

No revisions yet.