Sha256: 100f0e4f70cd3b32028db25214a45f0cef74ad139777d60a937e8149ba5e7eb9

Contents?: true

Size: 1.05 KB

Versions: 1

Compression:

Stored size: 1.05 KB

Contents

# option_initializer

Provides syntactic sugar for constructing objects with method chaining.

## Installation

```
gem install option_initializer
```

## Usage

```ruby
require 'option_initializer'

class Person
  include OptionInitializer
  option_initializer :id, :name, :age, :greetings
  option_validator do |k, v|
    case k
    when :age
      raise ArgumentError, "invalid age" if age < 0
    when :name
      raise ArgumentError, "invalid name" if name.empty?
    end
  end

  def initialize opts
    @options = opts
  end

  def say_hello
    puts @options[:greetings].call @options[:name]
  end
end

# Then
john = Person.
         name('John Doe').
         age(19).
         greetings { |name| "Hi, I'm #{name}!" }.
         id(1000).
         new

# becomes equivalent to
john = Person.new(
         :id => 1000,
         :name => 'John Doe',
         :age => 19,
         :greetings => proc { |name| "Hi, I'm #{name}!" }
       )

# Method call shortcut
Person.
  name('John Doe').
  age(19).
  greetings { |name| "Hi, I'm #{name}!" }.
  id(1000).
  say_hello
```

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
option_initializer-1.1.1 README.md