Sha256: ce87a219881104b50063b9f4159c467c26ee9e88df2a70429ea50d6aa4828802

Contents?: true

Size: 1.17 KB

Versions: 1

Compression:

Stored size: 1.17 KB

Contents

class G5Updatable::LocationsUpdater

  cattr_writer :on_update_callbacks

  def initialize(foundation_client)
    @client_uid   = foundation_client.uid
    @g5_locations = foundation_client.locations
  end

  def self.on_update(&block)
    self.on_update_callbacks ||= []
    self.on_update_callbacks += [block]
  end

  def self.on_update_callbacks
    @@on_update_callbacks || []
  end

  def update
    @g5_locations.each do |g5_location|
      attributes = g5_location.location_hash.dup
      location = G5Updatable::Location.
          find_or_initialize_by(uid: attributes[:uid]).
          update_attributes!(
              urn:        attributes[:urn],
              name:       attributes[:name],
              client_uid: attributes[:client_uid],
              properties: attributes,
              updated_at: DateTime.now
          )
      self.class.on_update_callbacks.each { |cb| cb.call(location) }
    end
    destroy_orphaned_locations!
  end

  private

  def destroy_orphaned_locations!
    if @g5_locations.empty?
      G5Updatable::Location.by_client_uid(@client_uid)
    else  
      G5Updatable::Location.where.not(urn: @g5_locations.map(&:urn))
    end.destroy_all
  end  
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
g5_updatable-0.7.0 lib/g5_updatable/locations_updater.rb