0.0
No commit activity in last 3 years
No release in over 3 years
Ruby module to provide initialize with magic options
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 0.9.2
~> 2.5.8
~> 2.6.0
 Project Readme

magic_options¶ ↑

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.

Examples¶ ↑

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

require 'rubygems'
require 'magic_options'

class Gullible

  include MagicOptions

  magic_initialize

end

Gullible.new :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

Cow.new :color => "brown", :gender => "female"
# => #<Cow:0x7f77e409a6d8 @gender="female", @color="brown">
Cow.new :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

end

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

Obtaining¶ ↑

To install from rubygems.org:

gem install magic_options

To fetch the source from github.com:

git clone git://github.com/sheldonh/magic_options.git

Credits¶ ↑

Written in colaboration with @rorymckinley