Class: Light::Model

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming, ActiveModel::Translation, ActiveSupport::Concern
Includes:
ActiveModel::Conversion, ActiveModel::Serialization, ActiveModel::Serializers::JSON, ActiveModel::Validations
Defined in:
lib/light/model.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Model



41
42
43
44
45
46
# File 'lib/light/model.rb', line 41

def initialize(params = {})
  return unless params
  params.each do |attr, value|
    public_send("#{attr}=", value)
  end
end

Class Method Details

.attributes(*attrs) ⇒ Object



13
14
15
16
17
18
# File 'lib/light/model.rb', line 13

def attributes(*attrs)
  attrs.each do |attr|
    send(:attr_accessor, attr)
  end
  @__attributes = (@__attributes || []) + attrs
end

.persisted_via_attr(attr_name) ⇒ Object



20
21
22
# File 'lib/light/model.rb', line 20

def persisted_via_attr(attr_name)
  @__persisted_via_attr = attr_name
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



31
32
33
# File 'lib/light/model.rb', line 31

def ==(other)
  other.class == self.class && other.equality_state == equality_state
end

#equality_stateObject



25
26
27
28
29
# File 'lib/light/model.rb', line 25

def equality_state
  self.class.instance_variable_get(:@__attributes).map do |attr|
    public_send(attr.to_s)
  end
end

#hashObject



37
38
39
# File 'lib/light/model.rb', line 37

def hash
  equality_state.hash
end

#persisted?Boolean



52
53
54
55
56
57
# File 'lib/light/model.rb', line 52

def persisted?
  attr_name = self.class.instance_variable_get(:@__persisted_via_attr)
  return false if attr_name.nil?
  value = send(attr_name)
  !(value.respond_to?(:empty?) ? !!value.empty? : !value)
end

#to_h(opts = nil) ⇒ Object



48
49
50
# File 'lib/light/model.rb', line 48

def to_h(opts = nil)
  serializable_hash(opts)
end