0.0
No commit activity in last 3 years
No release in over 3 years
Extremely simple value objects
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.3
>= 0
= 3.0.0.beta2
 Project Readme

StrictStruct Build Status Code Climate Gem Version Dependency Status

This gems aims to provide a modern version of Struct. While Struct is a nice and easy way to create a light-weight value object, it has some drawbacks

  • You need to remember the order of arguments
  • The object is mutable by default

This gem aims to avoid these drawbacks, while providing the ease of use of Struct.

Usage

If you want to create a simple object, just declare it like you would declare a Struct:

Rectangle = StrictStruct.new(:x, :y) do
  def area
    x * y
  end
end

This would conceptually create something like the following object:

class Rectange
  attr_reader :x, :y

  def initialize(x:, y:)
    @x = x
    @y = y
  end

  def to_h
    to_hash
  end

  def to_hash
    {
      x: x,
      y: y
    }
  end

  def area
    x * y
  end
end

Since this is meant to create immutable objects, the values aren't actually assigned to instance variables but saved internally in a hash.

Changing behavior

You can also choose to override behavior. You can just use super in the initialization block like you are used to with normal classes:

Rectangle = StrictStruct.new(:x, :y) do
  def area
    x * y
  end

  def to_hash
    super.merge({area: area})
  end
end

Installation

Add this line to your application's Gemfile:

gem 'strict_struct'

And then execute:

$ bundle

Or install it yourself as:

$ gem install strict_struct

Contributing

  1. Fork it
  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 new Pull Request