by Aman King
AttributeDriven is a Ruby module that
- allows declaring a list of attributes in a class,
- provides reader methods for the attributes
- allows instantiating the class via a hash argument that provides attribute values
- overrides equality and hash methods to check for field equality
Such a class, which is driven by its attributes rather than behaviour, is best suited for purposes similar to those of a Data Transfer Object or a View Object (eg: rendering data in a view template, results from XML parsing, etc). For most usages though, a class should be driven by its behaviour, with due attention given to encapsulation and whether it's a Value Object or an Entity Object (which dictates how the equality check is implemented).
AttributeDriven is available as a gem. Simply type the following: gem install attribute-driven
require 'attribute-driven' class Money include AttributeDriven attributes :value, :currency # initializes_with :value, :currency #=> only adds the initialize method # equality_based_on :value, :currency #=> only overrides equality methods and hash end money = Money.new(:value => 20, :currency => 'USD') #=> #<Money:0x5138e4 @value=20, @currency="USD"> money.value #=> 20 money.currency #=> "USD" money == Money.new(:value => 20, :currency => 'USD') #=> true
(see test/attribute_driven_test.rb for more)
Copyright 2009 Aman King
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.