as_value

Extend AsValue to create Ruby value objects; based on the ValueObject described by Martin Fowler in his book, 'Patterns of Enterprise Application Architecture'.


License
MIT
Install
gem install as_value -v 0.0.2

Documentation

AsValue

Create value objects in your Ruby projects with just a few lines of code. The generated objects adhere to the description of Value Objects as described by Martin Fowler in 'Patterns of Enterprise Application Architecture' (2002, Addison-Wesley Professional).

Installation

Add this line to your application's Gemfile:

gem 'as_value'

And then execute:

$ bundle

Or install it yourself as:

$ gem install as_value

Usage

Any Ruby object can be treated as a value object simply by extending AsValue::ValueObject and declaring the instance attributes:

class EmailAddress
  extend AsValue::ValueObject

  instance_attributes :email_address, :type
end

Given the above EmailAddress class:

$ email = EmailAddress.new(email_address: 'someone@example.com', type: :work)
  # => #<EmailAddress:0x007f1104b6d5e8 @email_address="someone@example.com", @type=:work>

$ email.email_address = 'someone.else@example.com'
  # => AsValue::ImmutableObjectError: ValueObjects are immutable -- write methods are unavailable.

Once initialized, value objects cannot be altered. If you need to change the value, create a new instance with the desired attributes.

Comparison of value objects only considers values of instance attributes; identity is not a factor:

$ email_1 = EmailAddress.new(email_address: 'xyz@example.com')
$ email_2 = EmailAddress.new(email_address: 'xyz@example.com')
$ email_1 == email_2    # => true
$ email_1.eql? email_2  # => true

The value comparison applies even if the objects are of different types:

class GenericObject
  extend AsValue::ValueObject

  instance_attributes :email_address, :type
end

...

$ email = EmailAddress.new(email_address: 'someone@example.com')
$ generic = GenericObject.new(email_address: 'someone@example.com')
$ email == generic      # => true
$ email.eql? generic    # => true

Contributing

  1. Fork it ( https://github.com/bradleyankrom/as_value/fork )
  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 a new Pull Request