# frozen_string_literal: true module Segmentor # Target is single piece of data, returned by a class Target < ActiveRecord::Base self.table_name = :segmentor_targets belongs_to :session, class_name: '::Segmentor::Session' belongs_to :segment, class_name: '::Segmentor::Segment' belongs_to :user validates :user_id, presence: true validates :user_id, uniqueness: { scope: :session_id } validates :segment_id, presence: true validates :session_id, presence: true before_validation :set_segment_if_nil def self.new_with_user(user) ::Segmentor::Target.new(user_id: user.id, payload: {}) end def self.new_with_user_and_payload(user, payload) ::Segmentor::Target.new(user_id: user.id, payload: payload) end def issue_receipt!(rendered_value = nil) ::Segmentor::Receipt.record_receipt(self, rendered_value) end def most_recent_receipt segment.receipts.where(user_id: user_id).order(:sent_at).last end def get_binding binding end def preview(&block) raise ArgumentError, 'block required' unless block_given? block.call(self, segment.notifier_context) end def can_be_notified? most_recent_receipt = segment.receipts.where(user_id: user_id).order(:sent_at).last # notification can be sent if there is a receipt for this target that # is older than the repeat frequency of its segment return true if most_recent_receipt.nil? # we have a receipt. notify only if: # segment repeat frequency is not NO_REPEAT # receipt is older than segment repeat frequency segment.repeat_frequency != ::Segmentor::Segment::NO_REPEAT && most_recent_receipt.sent_at < segment.repeat_frequency.days.ago end private def set_segment_if_nil self.segment_id ||= session.segment_id end end end