Module: Objectmancy::Objectable

Defined in:
lib/objectmancy/objectable.rb

Overview

Mixin for allowing your objects to take a Hash and turn them into an object. By default, the values will be whatever the value of the Hash at that key is.

Examples:

Including Objectable

class Kitten
  include Objectmancy::Objectable

  attribute :name
end

tabby = Kitten.new(name: 'Eddy')
tabby.name # => "Eddy"

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



24
25
26
# File 'lib/objectmancy/objectable.rb', line 24

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

Instance Method Details

#initialize(attrs = {}) ⇒ Object

Creates your object. You should use the after_initialize

Parameters:

  • attrs (Hash) (defaults to: {})

    Hash of attributes to create the object with



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/objectmancy/objectable.rb', line 94

def initialize(attrs = {})
  before_initialize

  _assignable_attributes(attrs).each do |attr, value|
    options = self.class.registered_attributes[attr.to_sym]

    value =
      if options.multiple
        _convert_multiples(value, options.type, options.objectable)
      else
        _single_value(value, options)
      end

    send("#{attr}=", value)
  end

  after_initialize
end