Sha256: 7a921c2e224f7f8bc7b235c54cceff57cf634d001b26000410de33da0ed09a80

Contents?: true

Size: 1.07 KB

Versions: 3

Compression:

Stored size: 1.07 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 v < 0
    when :name
      raise ArgumentError, "invalid name" if v.empty?
    end
  end

  def initialize opts
    validate_options 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

3 entries across 3 versions & 1 rubygems

Version Path
option_initializer-1.1.4 README.md
option_initializer-1.1.3 README.md
option_initializer-1.1.2 README.md