0.0
No commit activity in last 3 years
No release in over 3 years
NamedStruct is a drop-in replacement for Ruby's built-in Struct, that supports initialization via keyword arguments rather than positional arguments.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
 Dependencies

Development

~> 1.15
~> 5.0
~> 10.0
 Project Readme

NamedStruct

Travis Gem

NamedStruct is a replacement for Ruby's built-in Struct that accepts keyword arguments instead of positional arguments.

Why?

# bad
p = Point.new(1, 2)

# good
p = Point.new(x: 1, y: 2)

You probably don't need this

You could just add this file to your project and be done:

class NamedStruct < Struct
  def initialize(**kwargs)
    super(*members.map{|k| kwargs[k] })
  end
end

I found myself adding this class to every Ruby project I worked on, that's where a gem comes in handy.

Installation

NamedStruct is available as a RubyGem. To install, run:

gem install namedstruct

If you're using Bundler, add this to your Gemfile:

gem 'namedstruct'

Usage

Declaring a struct is the same as with Struct:

class Point < NamedStruct.new(:x, :y)
end

The only difference is in instantiating an object of the class:

# When using Ruby's struct:
p = Point.new(1, 2)

# When using NamedStruct:
p = Point.new(x: 1, y: 2)

Any arguments that are not provided will have a value of nil by default.

p = Point.new(x: 1)
p.x # => 1
p.y # => nil

Passing in an argument that isn't a member of the struct will raise an ArgumentError

p = Point.new(invalid_arg: something) # => Raises `ArgumentError`

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake test 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.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/rohitpaulk/named_struct. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the NamedStruct project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.