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
- Fork it ( https://github.com/bradleyankrom/as_value/fork )
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request