class Teneo::DataModel::Base

Public Class Methods

array_field(name) click to toggle source

Creates a virtual attribute <name>_list that converts between internal array storage and a ',' joined string

# File lib/teneo/data_model/base.rb, line 15
def self.array_field(name)
  # reader as <name>_list
  self.define_method "#{name}_list" do
    self.send(name).blank? ? '' : self.send(name).join(',')
  end
  # writer as <name>_list=
  self.define_method "#{name}_list=" do |values|
    self.send("#{name}=", [])
    self.send("#{name}=", values.split(',')) unless values.blank?
  end
end
create_from_hash(hash, id_tags, &block) click to toggle source
# File lib/teneo/data_model/base.rb, line 31
def self.create_from_hash(hash, id_tags, &block)
  id_tags = id_tags.map(&:to_sym)
  unless id_tags.empty? || id_tags.any? {|k| hash.include?(k)}
    raise ArgumentError, "Could not create '#{self.name}' object from Hash since none of the id tags '#{id_tags.join(',')}' are present"
  end
  tags = id_tags.inject({}) do |h, k|
    v = hash.delete(k)
    h[k] = v if v
    h
  end
  item = tags.empty? ? self.new : self.find_or_initialize_by(tags)
  item.attributes.clear
  block.call(item, hash) if block unless hash.empty?
  item.assign_attributes(tags.merge(hash))
  item.save!
  item
end
from_hash(hash, id_tags = [:name], &block) click to toggle source
# File lib/teneo/data_model/base.rb, line 27
def self.from_hash(hash, id_tags = [:name], &block)
  self.create_from_hash(hash, id_tags, &block)
end

Protected Class Methods

record_finder(model, query) click to toggle source
# File lib/teneo/data_model/base.rb, line 76
def self.record_finder(model, query)
  return model.where(query).take!
rescue ActiveRecord::RecordNotFound => e
  e.message.gsub!(/with .*$/, "with #{query}")
  raise e
end

Public Instance Methods

to_hash() click to toggle source
# File lib/teneo/data_model/base.rb, line 49
def to_hash
  result = self.attributes.reject {|k, v| v.blank? || volatile_attributes.include?(k)}
  result = result.to_yaml
  YAML.safe_load(result, symbolize_names: true, permitted_classes: [Time])
end
to_s() click to toggle source
# File lib/teneo/data_model/base.rb, line 55
def to_s
  (self.name rescue nil) || "#{self.class.name}_#{self.id}"
end

Protected Instance Methods

copy_attributes(other) click to toggle source
# File lib/teneo/data_model/base.rb, line 65
def copy_attributes(other)
  self.set(
      other.attributes.reject do |k, _|
        volatile_attributes.include? k.to_s
      end.each_with_object({}) do |(k, v), h|
        h[k] = v.duplicable? ? v.dup : v
      end
  )
  self
end
volatile_attributes() click to toggle source
# File lib/teneo/data_model/base.rb, line 61
def volatile_attributes
  %w'id created_at updated_at lock_version'
end