Project

attr_init

0.0
No commit activity in last 3 years
No release in over 3 years
Reader structs for ruby finally!.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.6
~> 0.7.0
~> 10.0
>= 0
~> 0.8.0

Runtime

>= 0
 Project Readme

AttrInit

Gem Version Build Status Coverage Status

So ruby has Struct but I never use it because:

  1. I have to extend the class with Struct
  2. It makes your instance_variables public
  3. It does not use hash initialization
  4. It does not support inheritance!!!

Installation

Add this line to your application's Gemfile:

gem 'attr_init'

And then execute:

$ bundle

Or install it yourself as:

$ gem install attr_init

Usage

Initializer

class Foo
  attr_init :a, :b
end

f = Foo.new(a: 0, b: 1)
=> #<Foo:0xb811601c @a=0, @b=1>

f.a
NoMethodError: undefined method: a' for #<Bar:0xb811601c @a=0, @b=1>

If you want to you can override it:

class Foo
  attr_init :a, :b
  def initialize(params, opt=nil)
    if opt.nil?
      do_other_initializer
    else
      attr_init(params)
    end
  end
end

Initializer with readers

class Bar
  reader_struct :a, :b
end

b = Bar.new(a: 0, b: 1)
=> #<Bar:0xaf11321c @a=0, @b=1>

b.a
=> 0

b.a = 2
NoMethodError: undefined method: a=' for #<Bar:0xb931e250 @a=0, @b=1>

Initializer with accessors

class Dah
  accessor_struct :a, :b
end

d = Dah.new(a: 0, b: 1)
=> #<Dah:0x81ad601c @a=0, @b=1>

d.a
=> 0

d.a = 2
=> 2

Struct adds #to_h

class Dah
  accessor_struct :a, :b
end

d = Dah.new(a: 0, b: 1)
=> #<Dah:0x81ad601c @a=0, @b=1>

d.to_h
=> {:a => 0, :b => 1}

Contributing

  1. Fork it ( https://github.com/[johnmcconnell]/attr_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