AttrInit
So ruby has Struct
but I never use it because:
- I have to extend the class with
Struct
- It makes your
instance_variables
public - It does not use hash initialization
- 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
- Fork it ( https://github.com/[johnmcconnell]/attr_init/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request