Skip to content
Ruby module for splatting an options hash into instance variables.
Find file
Latest commit 8a67efb Oct 1, 2011 @sheldonh Release 1.0.1



MagicOptions is a ruby module that provides mechanisms for splatting an options hash into an object's instance variables, typically during object initialization. Each key is taken as the name of an instance variable, to which the associated value is assigned.

Version 1.0.0 broke compatibility with previous versions, in the interests of being useful in subclasses and in initializers that take more than just an options hash.


The simplest approach is to use MagicOptions::ClassMethods#magic_initialize:

require 'rubygems'
require 'magic_options'

class Gullible

  include MagicOptions


end :accepts => "anything"
# => #<Gullible:0x7f77e407fdb0 @accepts="anything">

If you want an ArgumentError for options that don't have accessors:

class Cow

  include MagicOptions

  magic_initialize :only => :respond_to?

  attr_accessor :color, :gender

end :color => "brown", :gender => "female"
# => #<Cow:0x7f77e409a6d8 @gender="female", @color="brown"> :color => "brown", :gender => "female", :wheels => 4
# => ArgumentError: Unknown option wheels for new Cow

If your object initializer must do more than apply the magic options pattern, you can use MagicOptions#magic_options inside your initialize method. This example also illustrates a more explicit method of specifying which options are allowed:

class Professor < Staff

  include MagicOptions

  def initialize(name, options = {})
    magic_options options, :only => [:iq, :hairstyle]

end :hair_style => :einsteinian
# => #<Professor:0x7f77e406d980 @hair_style=:einsteinian> :does_not_take => :anything
# => ArgumentError: Unknown option does_not_take for new Professor


To install from

gem install magic_options

To fetch the source from

git clone git://


Written in colaboration with @rorymckinley

Something went wrong with that request. Please try again.