class Operationable::Serializer

Constants

RECORD_FIELDS
USER_FIELDS

Attributes

action_name[R]
activity[R]
params[R]
record[R]
result[R]
user[R]

Public Class Methods

new(record, user, params, result, activity, action_name) click to toggle source
# File lib/operationable/serializer.rb, line 9
def initialize(record, user, params, result, activity, action_name)
  @record = record
  @user = user
  @params = params
  @result = result
  @activity = activity
  @action_name = action_name
end

Public Instance Methods

serialize() click to toggle source
# File lib/operationable/serializer.rb, line 18
def serialize
  stringify_arguments(extract_props(record, user))
end

Private Instance Methods

acceptable_argument?(arg) click to toggle source
# File lib/operationable/serializer.rb, line 76
def acceptable_argument?(arg)
  [Numeric, String, NilClass].any? { |t| arg.is_a? t }
end
extract_from_record(record) click to toggle source
# File lib/operationable/serializer.rb, line 34
def extract_from_record(record)
  extracted_props = record_fields.each_with_object({}) do |field, result|
    result[field] = record.try(field)
    result
  end

  extracted_props[:name] = record.class.name

  extracted_props
end
extract_from_user(user) click to toggle source
# File lib/operationable/serializer.rb, line 45
def extract_from_user(user)
  user_fields.each_with_object({}) do |field, result|
    result["changed_by_#{field}".to_sym] = user.try(field)
    result
  end
end
extract_props(record, user) click to toggle source
# File lib/operationable/serializer.rb, line 24
def extract_props(record, user)
  {
    **extract_from_record(record),
    **extract_from_user(user),
    params: params,
    activity: activity,
    action_name: action_name
  }
end
record_fields() click to toggle source
# File lib/operationable/serializer.rb, line 52
def record_fields
  self.class.const_get('RECORD_FIELDS')
end
stringify_arguments(params) click to toggle source
# File lib/operationable/serializer.rb, line 60
def stringify_arguments(params)
  params.compact!

  params.transform_values! do |value|
    if value.is_a? Array
      value.map { |i| acceptable_argument?(i) ? i : i.to_s }
    elsif [Hash, HashWithIndifferentAccess, ActionController::Parameters].any? { |klass| value.is_a? klass }
      stringify_arguments(value.to_h)
    else
      acceptable_argument?(value) ? value : value.to_s
    end
  end

  params
end
user_fields() click to toggle source
# File lib/operationable/serializer.rb, line 56
def user_fields
  self.class.const_get('USER_FIELDS')
end