Module: Horcrux::Entity

Defined in:
lib/horcrux/entity.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



7
8
9
10
11
12
13
14
15
# File 'lib/horcrux/entity.rb', line 7

def self.included(base)
  class << base
    attr_accessor :attributes, :writable_attributes, :default_attribute
  end

  base.attributes = Set.new
  base.writable_attributes = Set.new
  base.extend ClassMethods
end

Instance Method Details

#==(other) ⇒ Object

Public



161
162
163
164
# File 'lib/horcrux/entity.rb', line 161

def ==(other)
  default_attr = self.class.default_attribute
  other.class == self.class && other.send(default_attr) == send(default_attr)
end

#each_attr(writable_only = false) ⇒ Object

Public



150
151
152
153
154
155
156
157
158
# File 'lib/horcrux/entity.rb', line 150

def each_attr(writable_only = false)
  attr_method = writable_only ? :writable_attributes : :attributes
  self.class.send(attr_method).each do |key|
    if value = send(key)
      yield key, value
    end
  end
  self
end

#initialize(hash = {}) ⇒ Object

Public



125
126
127
# File 'lib/horcrux/entity.rb', line 125

def initialize(hash = {})
  update_attrs(hash, all = true)
end

#to_hash(writable_only = false) ⇒ Object

Public: Converts the valid attributes into a Hash of Symbol key and Object value.

Returns a Hash.



170
171
172
173
174
175
176
# File 'lib/horcrux/entity.rb', line 170

def to_hash(writable_only = false)
  hash = {}
  each_attr(writable_only) do |key, value|
    hash[key.to_sym] = value
  end
  hash
end

#update_attrs(hash, all = false) ⇒ Object

Public: Updates multiple attributes.

hash - A Hash containing valid attributes.

Returns this Entity.



134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/horcrux/entity.rb', line 134

def update_attrs(hash, all = false)
  attr = all ? self.class.attributes : self.class.writable_attributes
  hash.each do |key, value|
    key_s = key.to_s
    
    if !attr.include?(key_s)
      raise ArgumentError, "Invalid property: #{key.inspect}"
    end

    send "#{key_s}=", value
  end

  self
end