Module: Traitorous

Defined in:
lib/traitorous.rb,
lib/traitorous/convert.rb,
lib/traitorous/equality.rb,
lib/traitorous/converter.rb,
lib/traitorous/standard_procs.rb

Overview

Traitorous is a model trait library whose primary goal is to be able to

import from a hash and have it initialize an object graph.  It also exports
back to a similar hash.

The exported hash will be almost identical to the import hash with the sole

exception being that any trait values that are left out of the initial hash
will end up being in the export hash with a nil value.

Similar libraries include github.com/solnic/virtus,

https://github.com/cgriego/active_attr, and https://github.com/jetrockets/attrio

Defined Under Namespace

Modules: ClassMethods, Convert, Equality, StandardProcs Classes: Converter

Constant Summary collapse

HASH =

Use the HashWithIndifferentAccess from the activesupport gem.

HashWithIndifferentAccess
VERSION =

Read the VERSION file in gem root to set version number.

File.read('VERSION')

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

:nodoc:



56
57
58
# File 'lib/traitorous.rb', line 56

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#exportObject



70
71
72
73
74
75
76
77
# File 'lib/traitorous.rb', line 70

def export
  exported = {}
  traits.each_pair do |trait_name, converter|
    attr_value = self.public_send(trait_name.intern)
    exported[trait_name] = converter.export(attr_value)
  end
  exported
end

#initialize(data = {}) ⇒ Object

use the key/value pairs of



61
62
63
64
65
66
67
68
# File 'lib/traitorous.rb', line 61

def initialize(data = {})
  raise "No traits have been defined for #{self.class}" unless self.class.traits
  @data = HASH.new(data)
  traits.each_pair do |new_trait, converter|
    val = converter.import(@data.fetch(new_trait, nil))
    self.send("#{new_trait}=".intern, val)
  end
end

#inspectObject



83
84
85
86
87
# File 'lib/traitorous.rb', line 83

def inspect
  string = "#<#{self.class.name}:#{self.object_id} "
  fields = self.class.traits.keys.map{|field| "#{field}: #{self.send(field).inspect}"}
  string << fields.join(", ") << ">"
end

#traitsObject



79
80
81
# File 'lib/traitorous.rb', line 79

def traits
  self.class.traits
end