0.0
No commit activity in last 3 years
No release in over 3 years
Gem that provides a keyword argument based initialize method to a class, executing the setter of all the recognised keywords.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

 Project Readme

KeywordInit

Gem that provides a keyword argument based initialize method to a class, executing the setter of all the recognised keywords.

Gem Version Build Status Code Climate Code Climate Coverage

Installation

Add this line to your application's Gemfile:

gem 'keyword_init'

And then execute:

$ bundle

Or install it yourself as:

$ gem install keyword_init

Usage

You can have the basic keyword initialization in your class, by including the KeywordInit module in your class. This will include the initialize method in the class.

For each keyword that the initialize method receives, it will execute the setter if that method exists (it will look for a method called keyword_name=).

It will ignore all keywords that don't have a valid setter.

class TestKlass
  include KeywordInit
  
  attr_accessor :attrib
  attr_writer :writeonly
  attr_reader :readonly
  
  def my_data
    {attrib: attrib, writeonly: writeonly, readonly: readonly}
  end
end

x = TestKlass.new attrib: 1, writeonly: 2, readonly: 3
x.attrib # => 1
# did not set the value because there is no `readonly=` method 
x.readonly # => nil

x.my_data # => {attrib: 1, writeonly: 2, readonly: nil}

Strict mode

if we include KeywordInit::Strict instead of KeywordInit or KeywordInit::Relaxed, when the initializer receives a key with no matching setter, it will raise a KeywordInit::KeyError exception.

class TestKlass
  include KeywordInit
  
  attr_accessor :attrib
  attr_writer :writeonly
  attr_reader :readonly
  
  def my_data
    {attrib: attrib, writeonly: writeonly, readonly: readonly}
  end
end

good = TestKlass.new attrib: 1, writeonly: 2
good.attrib # => 1
good.my_data # => {attrib: 1, writeonly: 2, readonly: nil}

bad =  TestKlass.new attrib: 1, writeonly: 2, readonly: 4
  # => raises KeywordInit::KeyError
 #
bad2 =  TestKlass.new attrib: 1, writeonly: 2, unknown: 4
  # => raises KeywordInit::KeyError 

Changelog

v1.5.0

supports strict mode.

v1.4.0 (renamed from v1.3.1)

supports passing nil to both initializer and _set_properties

v1.3.0

the work is done by a private method _set_properties that expects a hash of attributes. This way the work can be performed on an existing instance by calling that private method.

1.2.0

now works with private setters

TODO

  1. "direct" integration with fluent_accessors ?

Contributing

  1. Fork it ( https://github.com/eturino/keyword_init/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request