Sha256: 9a818341781a1af3603a20054c7a938baa261d2731c9f10cddcb88cf1fccd01d

Contents?: true

Size: 1.18 KB

Versions: 3

Compression:

Stored size: 1.18 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

3 entries across 3 versions & 1 rubygems

Version Path
g5_updatable-0.10.3 lib/g5_updatable/locations_updater.rb
g5_updatable-0.10.2 lib/g5_updatable/locations_updater.rb
g5_updatable-0.10.1 lib/g5_updatable/locations_updater.rb