Sha256: ffceeb2dfbfa4c2593edcb5e984205ce5741124442d4d4cb78806cc4770b3c8c

Contents?: true

Size: 1.19 KB

Versions: 4

Compression:

Stored size: 1.19 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])

      location.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))
        .where(client_uid: @client_uid)
    end.destroy_all
  end  
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
g5_updatable-0.10.0 lib/g5_updatable/locations_updater.rb
g5_updatable-0.9.0 lib/g5_updatable/locations_updater.rb
g5_updatable-0.8.0 lib/g5_updatable/locations_updater.rb
g5_updatable-0.7.2 lib/g5_updatable/locations_updater.rb