Sha256: aba4ec295bff8b6ae33319075e7f4075935a72d848ba5a04421121cadc3490fe

Contents?: true

Size: 1.88 KB

Versions: 2

Compression:

Stored size: 1.88 KB

Contents

require 'active_model'
require 'browsing_history/storage'

class BrowsingHistory::History
  extend  ActiveModel::Callbacks
  include ActiveModel::Model
  include ActiveModel::Validations

  include BrowsingHistory::Storage

  class ArgumentError < BrowsingHistory::Error; end

  attr_accessor :browser, :historizable, :expiration

  define_model_callbacks :save

  after_save :save_to_storage

  validate :valid_browser, :valid_historizable

  def initialize(browser: nil, historizable: nil)
    @browser      = browser
    @historizable = historizable
  end

  def save
    valid? ? run_callbacks(:save) { true } : false
  end

  def save!
    valid? ? run_callbacks(:save) { true } : raise_errors
  end

  class << self
    def create(attributes = {})
      instance = new(**attributes)
      instance.save ? instance : false
    end

    def create!(attributes = {})
      instance = new(**attributes)
      instance.save!
      instance
    end

    def where(browser: nil, historizable: nil, **opts)
      return [] if !browser && !historizable

      current_storage.fetch(browser, historizable, opts)
    end

    def count(browser: nil, historizable: nil)
      return 0 if !browser && !historizable
      current_storage.count(browser, historizable)
    end
  end

  private

  def save_to_storage
    self.class.current_storage.add(browser, historizable)
  end

  def valid_browser
    if !browser.respond_to?(:browser_id) &&
        !browser.respond_to?(:browser_type)
      errors.add :browser, ':browser in args is not browser!!'
    end
  end

  def valid_historizable
    if !historizable.respond_to?(:historizable_id) &&
        !historizable.respond_to?(:historizable_type)
      errors.add :historizable, ':historizable in args is not historizable!!'
    end
  end

  def raise_errors
    errors.each do |_, message|
      if message =~ /args/
        raise ArgumentError, message
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
browsing_history-0.0.3 lib/browsing_history/history.rb
browsing_history-0.0.2 lib/browsing_history/history.rb