Mimicking Ruby’s OpenStruct Class with method_missing()

Ruby’s OpenStruct class instantiates object with getter and setter methods that can be dynamically defined, so the object behaves like a hash This post shows how to use method_missing() to create a class that behaves similarly to the built-in OpenStruct class.

We’ll start by demonstrating the functionality of the built-in OpenStruct() class:

require 'ostruct'
phish = OpenStruct.new
phish.fluffhead # => nil
phish.fluffhead = 'was a man'
phish.fluffhead # => 'was a man'

OpenStruct objects return nil for attributes that are not defined. When new attributes are defined, they are accessible with a getter method.

Getter and setter methods are responsible for retrieving and setting instance variable values. method_missing() can be used in conjunction with instance_variable_get() and instance_variable_set() to create a class that behaves like OpenStruct.

class MyOpenStruct
  private
  def method_missing(name, *args)
    iv = "@#{name.to_s}"
    if name[-1] == '='
      instance_variable_set(iv.chop, args.first)
    else
      instance_variable_get(iv)
    end
  end
end

c = MyOpenStruct.new
c.bob = 'lob'
p c.bob # => 'lob'
p c.phil # => nil
c.phil = 'phhhhhil'
p c.phil # => 'phhhhhil'
p c.instance_variables # => [:@bob, :@phil]

This blog post was inspired by Metaprogramming Ruby, a must-read book for all Ruby programmers.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s