Class: Common::Base

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming
Includes:
ActiveModel::Serialization, Comparable
Defined in:
lib/common/models/base.rb

Overview

This is a base serialization class

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(init_attributes = {}) ⇒ Base

Returns a new instance of Base.



51
52
53
54
55
56
# File 'lib/common/models/base.rb', line 51

def initialize(init_attributes = {})
  super(init_attributes[:data] || init_attributes)
  @metadata = init_attributes[:metadata] || {}
  @errors_hash = init_attributes[:errors] || {}
  @original_attributes = attributes
end

Instance Attribute Details

#errors_hashObject

Returns the value of attribute errors_hash.



14
15
16
# File 'lib/common/models/base.rb', line 14

def errors_hash
  @errors_hash
end

#metadataObject

Returns the value of attribute metadata.



14
15
16
# File 'lib/common/models/base.rb', line 14

def 
  @metadata
end

Class Method Details

.default_sortObject



37
38
39
40
41
42
# File 'lib/common/models/base.rb', line 37

def default_sort
  @default_sort ||= begin
    sortable_attributes
    @default_sort
  end
end

.filterable_attributesObject



44
45
46
47
48
# File 'lib/common/models/base.rb', line 44

def filterable_attributes
  @filterable_attributes ||= attribute_set.map do |attribute|
    [attribute.name.to_s, attribute.options[:filterable]] if attribute.options[:filterable]
  end.compact.to_h.with_indifferent_access
end

.max_per_page(value = nil) ⇒ Object



21
22
23
# File 'lib/common/models/base.rb', line 21

def max_per_page(value = nil)
  @max_per_page ||= value || 100
end

.per_page(value = nil) ⇒ Object



17
18
19
# File 'lib/common/models/base.rb', line 17

def per_page(value = nil)
  @per_page ||= value || 10
end

.sortable_attributesObject



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/common/models/base.rb', line 25

def sortable_attributes
  @sortable_attributes ||= attribute_set.map do |attribute|
    next unless attribute.options[:sortable]

    sortable = attribute.options[:sortable].is_a?(Hash) ? attribute.options[:sortable] : { order: 'ASC' }
    if sortable[:default]
      @default_sort ||= sortable[:order] == 'DESC' ? "-#{attribute.name}" : attribute.name.to_s
    end
    [attribute.name.to_s, sortable[:order]]
  end.compact.to_h.with_indifferent_access
end

Instance Method Details

#changedObject



62
63
64
# File 'lib/common/models/base.rb', line 62

def changed
  attributes.map { |k, v| k if @original_attributes[k] != v }.compact
end

#changed?Boolean

Returns:

  • (Boolean)


58
59
60
# File 'lib/common/models/base.rb', line 58

def changed?
  changed.any?
end

#changesObject



66
67
68
# File 'lib/common/models/base.rb', line 66

def changes
  changed.map { |k, _v| [k, [@original_attributes[k], attributes[k]]] }.to_h
end