class Unavailability::UnavailableDates::Add

Attributes

dateable[R]
from[R]
to[R]

Public Class Methods

new(dateable, from, to) click to toggle source
# File lib/unavailability/unavailable_dates/add.rb, line 4
def initialize(dateable, from, to)
  @dateable = dateable
  @from    = from
  @to      = to

  raise ArgumentError.new('from has to be a Date') unless @from.is_a?(Date)
  raise ArgumentError.new('to has to be a Date') unless @to.is_a?(Date)
end

Public Instance Methods

call() click to toggle source
# File lib/unavailability/unavailable_dates/add.rb, line 17
def call
  if overlappings.empty?
    unavailable_dates.create(
      from: from,
      to: to
    )
  else
    overlappings.each do |unavailability|
      update(unavailability, from, to)
    end

    merge(overlappings)
  end

  dateable
end
unavailable_dates() click to toggle source
# File lib/unavailability/unavailable_dates/add.rb, line 13
def unavailable_dates
  dateable.unavailable_dates
end

Private Instance Methods

merge(overlappings) click to toggle source
# File lib/unavailability/unavailable_dates/add.rb, line 55
def merge(overlappings)
  from = overlappings.map(&:from).min
  to = overlappings.map(&:to).max
  overlappings.each(&:destroy)
  unavailable_dates.create(from: from, to: to)
end
overlappings() click to toggle source
# File lib/unavailability/unavailable_dates/add.rb, line 38
def overlappings
  unavailable_dates.overlapping_including_nabour(from, to)
end
update(unavailability, from, to) click to toggle source
# File lib/unavailability/unavailable_dates/add.rb, line 42
def update(unavailability, from, to)
  if from < unavailability.from
    if to > unavailability.to
      unavailability.update(from: from)
      unavailability.update(to: to)
    else
      unavailability.update(from: from)
    end
  elsif to > unavailability.to
    unavailability.update(to: to)
  end
end