Module: MagicOptions
- Defined in:
- lib/magic_options.rb,
lib/magic_options/version.rb
Overview
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.
For example:
<tt>
class Cow
def initialize(name, = {})
@name = name.capitalize
@color = color
@gender = gender
end
end
Cow.new('Daisy', :color => 'brown', :gender => 'female')
# => #<Cow:0x000000015d02b8 @color="brown", @gender="female", @name="Daisy">
</tt>
Here’s how the same object initializer might be defined with MagicOptions:
<tt>
class Cow
include MagicOptions
def initialize(name, = {})
@name = name.capitalize
(, :only => [:color, :gender])
end
end
</tt>
If your initialize method does nothing other than implement the magic options pattern, you can let MagicOptions::ClassMethods#magic_initialize define it for you instead.
Defined Under Namespace
Modules: ClassMethods
Constant Summary collapse
- VERSION =
The version of the MagicOptions gem.
"1.0.1"
Class Method Summary collapse
-
.included(base) ⇒ Object
:nodoc:.
Instance Method Summary collapse
-
#magic_options(options, config = {}) ⇒ Object
Assign every value from the options hash into an instance variable named after the associated key.
Class Method Details
.included(base) ⇒ Object
:nodoc:
63 64 65 |
# File 'lib/magic_options.rb', line 63 def self.included(base) # :nodoc: base.extend(ClassMethods) end |
Instance Method Details
#magic_options(options, config = {}) ⇒ Object
Assign every value from the options hash into an instance variable named after the associated key. The optional config hash may impose constraints on this behaviour as follows:
:only
-
Specify the only options that are allowed. The special value
:respond_to?
specifies that options are allowed if they name a method on the instance. :require
-
Specify options that must be passed. Options specified in
:require
do not also need to be specified in:only
.
Raises:
- ArgumentError
-
when
:only
is specified and an option is passed that is not in:only
or:require
- ArgumentError
-
when
:require
specifies one or more options that are not passed
56 57 58 59 60 61 |
# File 'lib/magic_options.rb', line 56 def (, config = {}) (, config) .each do |option, value| instance_variable_set "@#{option}", value end end |