Another approach to reduce initialization boilerplate
Add this line to your application's Gemfile:
gem 'def_initialize'And then execute:
$ bundle
Or install it yourself as:
$ gem install def_initialize
class Employee
include DefInitialize.with("name, uuid = SecureRandom.uuid, *params, age:, position: 'manager', **opts")
end
# is the same as:
class Employee
def initialize(name, uuid = SecureRandom.uuid, *params, age:, position: 'manager', **opts)
@name = name
@uuid = uuid
@params = params
@age = age
@position = position
@opts = opts
end
private
attr_reader :name, :uuid, :params, :age, :position, :opts
endBy convention, parameters starting with underscore symbol '_' are ignored:
class Point
include DefInitialize.with("x, y, _c")
end
# transforms to:
class Point
def initialize(x, y, _c) # Note that `_c` is still required to pass
@x = x
@y = y
end
private
attr_reader :x, :y
endAlternatively, you can extend a class with DefInitialize::DSL and use def_initialize method. Note, how close it looks to the native declaration!
class Base
extend DefInitialize::DSL
end
class Circle < Base
def_initialize("radius")
end
class Rectangle < Base
def_initialize("length, width")
endYou can specify level of access for your readers and writers:
class Person < Base
def_initialize("name", readers: :public, writers: :private)
end
# transforms to:
class Person
def initialize(name)
@name = name
end
attr_reader :name
private
attr_writer :name
endAllowed values are :public, :private, :protected and nil. If value is nil, accessors won't be defined at all.
default value for readers is private, default value for writers is nil
Just write plain old def initialize.
After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.
Bug reports and pull requests are welcome on GitHub at https://github.com/antoshalee/def_initialize.
The gem is available as open source under the terms of the MIT License.