1. Aman King
  2. attribute-driven

Wiki

Clone wiki

attribute-driven / Home

AttributeDriven

by Aman King

AttributeDriven is a Ruby module that

  1. allows declaring a list of attributes in a class,
  2. provides reader methods for the attributes
  3. allows instantiating the class via a hash argument that provides attribute values
  4. 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

Example

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)

License

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

http://www.apache.org/licenses/LICENSE-2.0

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.

Updated