├── .gitignore ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── Gemfile ├── LICENSE.txt ├── README.md ├── Rakefile ├── bin ├── console └── setup ├── lib └── namedstruct.rb ├── namedstruct.gemspec └── test ├── named_struct_test.rb └── test_helper.rb /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /Gemfile.lock 4 | /_yardoc/ 5 | /coverage/ 6 | /doc/ 7 | /pkg/ 8 | /spec/reports/ 9 | /tmp/ 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | sudo: false 3 | cache: bundler 4 | 5 | rvm: 6 | - 2.4.2 7 | - 2.3.5 8 | - 2.2.8 9 | - 2.1.10 10 | - 2.0.0 11 | - ruby-head 12 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at rohitpaulk@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } 4 | 5 | # Specify your gem's dependencies in named_struct.gemspec 6 | gemspec 7 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017 Paul Kuruvilla 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NamedStruct 2 | 3 | [![Travis](https://img.shields.io/travis/rohitpaulk/named_struct.svg)](https://travis-ci.org/rohitpaulk/named_struct) [![Gem](https://img.shields.io/gem/v/namedstruct.svg)](https://rubygems.org/gems/namedstruct) 4 | 5 | `NamedStruct` is a replacement for Ruby's built-in 6 | [`Struct`](https://ruby-doc.org/core-2.4.0/Struct.html) that accepts keyword 7 | arguments instead of positional arguments. 8 | 9 | ## Why? 10 | 11 | ```ruby 12 | # bad 13 | p = Point.new(1, 2) 14 | 15 | # good 16 | p = Point.new(x: 1, y: 2) 17 | ``` 18 | 19 | ## You probably don't need this 20 | 21 | You could just add this file to your project and be done: 22 | 23 | ```ruby 24 | class NamedStruct < Struct 25 | def initialize(**kwargs) 26 | super(*members.map{|k| kwargs[k] }) 27 | end 28 | end 29 | ``` 30 | 31 | I found myself adding this class to every Ruby project I worked on, that's 32 | where a gem comes in handy. 33 | 34 | ## Installation 35 | 36 | `NamedStruct` is available as a [RubyGem](https://rubygems.org/). To install, 37 | run: 38 | 39 | ``` 40 | gem install namedstruct 41 | ``` 42 | 43 | If you're using [Bundler](http://bundler.io/), add this to your Gemfile: 44 | 45 | ```ruby 46 | gem 'namedstruct' 47 | ``` 48 | 49 | ## Usage 50 | 51 | Declaring a struct is the same as with 52 | [Struct](https://ruby-doc.org/core-2.4.0/Struct.html): 53 | 54 | ```ruby 55 | class Point < NamedStruct.new(:x, :y) 56 | end 57 | ``` 58 | 59 | The only difference is in instantiating an object of the class: 60 | 61 | ```ruby 62 | # When using Ruby's struct: 63 | p = Point.new(1, 2) 64 | 65 | # When using NamedStruct: 66 | p = Point.new(x: 1, y: 2) 67 | ``` 68 | 69 | Any arguments that are not provided will have a value of `nil` by default. 70 | 71 | ```ruby 72 | p = Point.new(x: 1) 73 | p.x # => 1 74 | p.y # => nil 75 | ``` 76 | 77 | Passing in an argument that isn't a member of the struct will raise an 78 | `ArgumentError` 79 | 80 | ```ruby 81 | p = Point.new(invalid_arg: something) # => Raises `ArgumentError` 82 | ``` 83 | 84 | ## Development 85 | 86 | After checking out the repo, run `bin/setup` to install dependencies. Then, run 87 | `rake test` to run the tests. You can also run `bin/console` for an interactive 88 | prompt that will allow you to experiment. 89 | 90 | To install this gem onto your local machine, run `bundle exec rake install`. To 91 | release a new version, update the version number in `version.rb`, and then run 92 | `bundle exec rake release`, which will create a git tag for the version, push 93 | git commits and tags, and push the `.gem` file to 94 | [rubygems.org](https://rubygems.org). 95 | 96 | ## Contributing 97 | 98 | Bug reports and pull requests are welcome on GitHub at 99 | https://github.com/rohitpaulk/named_struct. This project is intended to be a 100 | safe, welcoming space for collaboration, and contributors are expected to 101 | adhere to the [Contributor Covenant](http://contributor-covenant.org) code of 102 | conduct. 103 | 104 | ## License 105 | 106 | The gem is available as open source under the terms of the [MIT 107 | License](http://opensource.org/licenses/MIT). 108 | 109 | ## Code of Conduct 110 | 111 | Everyone interacting in the NamedStruct project’s codebases, issue trackers, 112 | chat rooms and mailing lists is expected to follow the [code of 113 | conduct](https://github.com/[USERNAME]/named_struct/blob/master/CODE_OF_CONDUCT.md). 114 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require "bundler/gem_tasks" 2 | require "rake/testtask" 3 | 4 | Rake::TestTask.new(:test) do |t| 5 | t.libs << "test" 6 | t.libs << "lib" 7 | t.test_files = FileList["test/**/*_test.rb"] 8 | end 9 | 10 | task :default => :test 11 | -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require "bundler/setup" 4 | require "named_struct" 5 | 6 | # You can add fixtures and/or initialization code here to make experimenting 7 | # with your gem easier. You can also use a different console, if you like. 8 | 9 | # (If you use this, don't forget to add pry to your Gemfile!) 10 | # require "pry" 11 | # Pry.start 12 | 13 | require "irb" 14 | IRB.start(__FILE__) 15 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | set -vx 5 | 6 | bundle install 7 | 8 | # Do any other automated setup that you need to do here 9 | -------------------------------------------------------------------------------- /lib/namedstruct.rb: -------------------------------------------------------------------------------- 1 | class NamedStruct < Struct 2 | # Allow initialization via positional arguments. 3 | def initialize(**kwargs) 4 | kwargs.each{ |k, v| 5 | if members.include?(k) 6 | self[k] = v 7 | else 8 | raise ArgumentError, "Unknown named struct member: #{k}" 9 | end 10 | } 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /namedstruct.gemspec: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | lib = File.expand_path("../lib", __FILE__) 3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 4 | 5 | Gem::Specification.new do |spec| 6 | spec.name = "namedstruct" 7 | spec.version = "0.2.2" 8 | spec.authors = ["Paul Kuruvilla"] 9 | spec.email = ["rohitpaulk@gmail.com"] 10 | 11 | spec.summary = "A replacement for Struct that supports keyword arguments" 12 | spec.description = "NamedStruct is a drop-in replacement for Ruby's " + 13 | "built-in Struct, that supports initialization via " + 14 | "keyword arguments rather than positional arguments." 15 | spec.homepage = "https://github.com/rohitpaulk/named_struct" 16 | spec.license = "MIT" 17 | 18 | spec.files = `git ls-files -z`.split("\x0").reject do |f| 19 | f.match(%r{^(test|spec|features)/}) 20 | end 21 | spec.require_paths = ["lib"] 22 | 23 | spec.add_development_dependency "bundler", "~> 1.15" 24 | spec.add_development_dependency "rake", "~> 10.0" 25 | spec.add_development_dependency "minitest", "~> 5.0" 26 | end 27 | -------------------------------------------------------------------------------- /test/named_struct_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class NamedStructTest < Minitest::Test 4 | class ClassForTestKeywordArguments < NamedStruct.new(:x, :y) 5 | end 6 | 7 | def teardown 8 | # Remove class defined in tests 9 | if NamedStruct.constants.include?(:Point) 10 | NamedStruct.send(:remove_const, :Point) 11 | end 12 | end 13 | 14 | def test_keyword_arguments 15 | point = ClassForTestKeywordArguments.new(x: 1, y: 2) 16 | assert_equal(point.x, 1) 17 | assert_equal(point.y, 2) 18 | end 19 | 20 | def test_keyword_arguments_for_dynamic_class 21 | NamedStruct.new("Point", :x, :y) 22 | point = NamedStruct::Point.new(x: 1, y: 2) 23 | assert_equal(point.x, 1) 24 | assert_equal(point.y, 2) 25 | end 26 | 27 | def test_missing_values_are_nil 28 | NamedStruct.new("Point", :x, :y) 29 | point = NamedStruct::Point.new(x: 1) 30 | assert_nil(point.y) 31 | end 32 | 33 | def test_argument_error_if_bogus_argument_provided 34 | NamedStruct.new("Point", :x, :y) 35 | exception = assert_raises ArgumentError do 36 | NamedStruct::Point.new(invalid_arg: "dummy") 37 | end 38 | 39 | assert_equal("Unknown named struct member: invalid_arg", exception.message) 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) 2 | require "namedstruct" 3 | 4 | require "minitest/autorun" 5 | --------------------------------------------------------------------------------