Class: SparkApi::Models::Listing

Inherits:
Base
  • Object
show all
Extended by:
Finders
Defined in:
lib/spark_api/models/listing.rb

Constant Summary collapse

DATA_MASK =
"********"
WRITEABLE_FIELDS =
["ListPrice", "ExpirationDate"]

Constants included from Paginate

Paginate::DEFAULT_PAGE_SIZE

Instance Attribute Summary collapse

Attributes inherited from Base

#attributes, #errors, #parent

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Finders

find, find_one, first, last

Methods inherited from Base

#connection, connection, count, element_name, element_name=, first, get, #id, #load, #parse_id, path, #path, #persisted?, prefix, prefix=, #resource_pluralized, #resource_uri, #to_param, #to_partial_path

Methods included from Paginate

#collect, #paginate, #per_page

Methods included from Dirty

#changed, #changed?, #changed_attributes, #changes, #dirty_attributes, #previous_changes

Constructor Details

#initialize(attributes = {}) ⇒ Listing

Returns a new instance of Listing.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/spark_api/models/listing.rb', line 11

def initialize(attributes={})
  @photos = []
  @videos = []
  @virtual_tours = []
  @rental_calendars = []
  @documents = []
  @constraints = []
  @tour_of_homes = []
  @open_houses = []

  if attributes.has_key?('StandardFields')
    pics, vids, tours, docs, ohouses, tourhomes = attributes['StandardFields'].values_at('Photos','Videos', 'VirtualTours', 'Documents', 'OpenHouses', 'TourOfHomes')
  end

  if attributes.has_key?('RentalCalendar')
    rentalcalendars = attributes['RentalCalendar']
  end

  if pics != nil
    setup_attribute(@photos, pics, Photo)
    attributes['StandardFields'].delete('Photos')
  end

  if vids != nil
    setup_attribute(@videos, vids, Video)
    attributes['StandardFields'].delete('Videos')
  end

  if tours != nil
    setup_attribute(@virtual_tours, tours, VirtualTour)
    attributes['StandardFields'].delete('VirtualTours')
  end

  if docs != nil
    setup_attribute(@documents, docs, Document)
    attributes['StandardFields'].delete('Documents')
  end

  if ohouses != nil
    setup_attribute(@open_houses, ohouses, OpenHouse)
    attributes['StandardFields'].delete('OpenHouses')
  end

  if tourhomes != nil
    setup_attribute(@tour_of_homes, tourhomes, TourOfHome)
    attributes['StandardFields'].delete('TourOfHomes')
  end

  if rentalcalendars != nil
    setup_attribute(@rental_calendars, rentalcalendars, RentalCalendar)
    attributes.delete('RentalCalendar')
  end

  super(attributes)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_symbol, *arguments) ⇒ Object (private)

TODO trim this down so we’re only overriding the StandardFields access



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/spark_api/models/listing.rb', line 260

def method_missing(method_symbol, *arguments)
  method_name = method_symbol.to_s

  if method_name =~ /(=|\?)$/
    case $1
    when "="
      write_attribute($`,arguments.first)
      # TODO figure out a nice way to present setters for the standard fields
    when "?"
      attributes[$`]
    end  
  else 
    return attributes[method_name] if attributes.include?(method_name)
    return @attributes['StandardFields'][method_name] if attributes['StandardFields'].include?(method_name)
    super
  end
end

Instance Attribute Details

#constraintsObject

Returns the value of attribute constraints.



6
7
8
# File 'lib/spark_api/models/listing.rb', line 6

def constraints
  @constraints
end

#documentsObject

Returns the value of attribute documents.



5
6
7
# File 'lib/spark_api/models/listing.rb', line 5

def documents
  @documents
end

#open_houses(arguments = {}) ⇒ Object

Returns the value of attribute open_houses.



5
6
7
# File 'lib/spark_api/models/listing.rb', line 5

def open_houses
  @open_houses
end

#photosObject

Returns the value of attribute photos.



5
6
7
# File 'lib/spark_api/models/listing.rb', line 5

def photos
  @photos
end

#rental_calendars(arguments = {}) ⇒ Object

Returns the value of attribute rental_calendars.



5
6
7
# File 'lib/spark_api/models/listing.rb', line 5

def rental_calendars
  @rental_calendars
end

#tour_of_homes(arguments = {}) ⇒ Object

Returns the value of attribute tour_of_homes.



5
6
7
# File 'lib/spark_api/models/listing.rb', line 5

def tour_of_homes
  @tour_of_homes
end

#videosObject

Returns the value of attribute videos.



5
6
7
# File 'lib/spark_api/models/listing.rb', line 5

def videos
  @videos
end

#virtual_toursObject

Returns the value of attribute virtual_tours.



5
6
7
# File 'lib/spark_api/models/listing.rb', line 5

def virtual_tours
  @virtual_tours
end

Class Method Details

.company(arguments = {}) ⇒ Object



80
81
82
# File 'lib/spark_api/models/listing.rb', line 80

def self.company(arguments={})
  collect(connection.get("/company/listings", arguments))
end

.find_by_cart_id(cart_id, options = {}) ⇒ Object



67
68
69
70
# File 'lib/spark_api/models/listing.rb', line 67

def self.find_by_cart_id(cart_id, options={}) 
  query = {:_filter => "ListingCart Eq '#{cart_id}'"}
  find(:all, options.merge(query)) 
end

.my(arguments = {}) ⇒ Object



72
73
74
# File 'lib/spark_api/models/listing.rb', line 72

def self.my(arguments={})
  collect(connection.get("/my/listings", arguments))
end

.nearby(latitude, longitude, arguments = {}) ⇒ Object



84
85
86
87
# File 'lib/spark_api/models/listing.rb', line 84

def self.nearby(latitude, longitude, arguments={})
  nearby_args = {:_lat => latitude, :_lon => longitude}.merge(arguments)
  collect(connection.get("/listings/nearby", nearby_args))
end

.office(arguments = {}) ⇒ Object



76
77
78
# File 'lib/spark_api/models/listing.rb', line 76

def self.office(arguments={})
  collect(connection.get("/office/listings", arguments))
end

.tour_of_homes(arguments = {}) ⇒ Object



89
90
91
# File 'lib/spark_api/models/listing.rb', line 89

def self.tour_of_homes(arguments={})
  collect(connection.get("/listings/tourofhomes", arguments))
end

Instance Method Details

#delete_photos(photoIds, args = {}) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/spark_api/models/listing.rb', line 242

def delete_photos(photoIds, args={})
  unless photoIds.is_a? String
    raise ArgumentError, "Batch photo delete failed. '#{photoIds}' is not a string."
  end

  begin
    return delete_photos!(photoIds, args)
  rescue BadResourceRequest => e
    SparkApi.logger.warn { "Failed to delete photos from resource #{self}: #{e.message}" }
  rescue NotFound => e
    SparkApi.logger.error { "Failed to delete photos from resource #{self}: #{e.message}" }
  end
  false
end

#delete_photos!(photoIds, args = {}) ⇒ Object



238
239
240
# File 'lib/spark_api/models/listing.rb', line 238

def delete_photos!(photoIds, args={})
  connection.delete subresource_path("photos") + "/#{photoIds}", args
end

#editable?(editable_settings = []) ⇒ Boolean

Returns:

  • (Boolean)


214
215
216
217
218
219
220
221
# File 'lib/spark_api/models/listing.rb', line 214

def editable?(editable_settings = [])
  settings = Array(editable_settings)
  editable = attributes.include?("Permissions") && self.Permissions["Editable"] == true
  if editable
    settings.each{ |setting| editable = false unless self.Permissions["EditableSettings"][setting.to_s] == true }
  end
  editable
end

#ExpirationDateObject



223
224
225
# File 'lib/spark_api/models/listing.rb', line 223

def ExpirationDate
  attributes["ExpirationDate"]
end

#ExpirationDate=(value) ⇒ Object



226
227
228
# File 'lib/spark_api/models/listing.rb', line 226

def ExpirationDate=(value)
  write_attribute("ExpirationDate", value)
end

#full_addressObject



139
140
141
# File 'lib/spark_api/models/listing.rb', line 139

def full_address
  "#{self.street_address}, #{self.region_address}".strip().gsub(/^,\s/, '').gsub(/,$/, '')
end

#my_notesObject



109
110
111
112
113
114
# File 'lib/spark_api/models/listing.rb', line 109

def my_notes
  Note.build_subclass.tap do |note|
    note.prefix = "/listings/#{self.ListingKey}"
    note.element_name = "/my/notes"
  end
end

#region_addressObject



135
136
137
# File 'lib/spark_api/models/listing.rb', line 135

def region_address
  "#{self.City}, #{self.StateOrProvince} #{self.PostalCode}".delete(DATA_MASK).strip().gsub(/^,\s/, '').gsub(/,$/, '')
end

#reorder_photo(photo_id, index) ⇒ Object



195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/spark_api/models/listing.rb', line 195

def reorder_photo(photo_id, index)
  unless Integer(index)
    raise ArgumentError, "Photo reorder failed. '#{index}' is not a number."
  end

  begin
    return reorder_photo!(photo_id, index)
  rescue BadResourceRequest => e
    SparkApi.logger.warn { "Failed to save resource #{self}: #{e.message}" }
  rescue NotFound => e
    SparkApi.logger.error { "Failed to save resource #{self}: #{e.message}" }
  end
  false
end

#reorder_photo!(photo_id, index) ⇒ Object



209
210
211
212
# File 'lib/spark_api/models/listing.rb', line 209

def reorder_photo!(photo_id, index)
  connection.put subresource_path("photos") + "/#{photo_id}", "Photos" => [{"Order"=>index}]
  true
end

#reorder_photos(arguments = {}) ⇒ Object



180
181
182
183
184
185
186
187
188
189
# File 'lib/spark_api/models/listing.rb', line 180

def reorder_photos(arguments={})
  begin
    return reorder_photos!(arguments)
  rescue BadResourceRequest => e
    SparkApi.logger.warn { "Failed to save resource #{self}: #{e.message}" }
  rescue NotFound => e
    SparkApi.logger.error { "Failed to save resource #{self}: #{e.message}" }
  end
  false
end

#reorder_photos!(arguments = {}) ⇒ Object



190
191
192
193
# File 'lib/spark_api/models/listing.rb', line 190

def reorder_photos!(arguments={})
  results = connection.put subresource_path("photos"), arguments
  true
end

#respond_to?(method_symbol, include_all = false) ⇒ Boolean

Returns:

  • (Boolean)


230
231
232
233
234
235
236
# File 'lib/spark_api/models/listing.rb', line 230

def respond_to?(method_symbol, include_all=false)
  if super
    true
  else
    attributes['StandardFields'].include?(method_symbol.to_s) rescue false
  end
end

#save(arguments = {}) ⇒ Object



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/spark_api/models/listing.rb', line 143

def save(arguments={})
  self.errors = []
  begin
    return save!(arguments)
  rescue BadResourceRequest => e
    self.errors << {:code => e.code, :message => e.message}
    if e.code == 1053
      @constraints = []
      e.details.each do |detail|
        detail.each_pair do |k,v|
          v.each { |constraint| @constraints << Constraint.new(constraint)}
        end
      end
    end
    SparkApi.logger.warn { "Failed to save resource #{self}: #{e.message}" }
  rescue NotFound => e
    SparkApi.logger.error { "Failed to save resource #{self}: #{e.message}" }
  end
  false
end

#save!(arguments = {}) ⇒ Object



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/spark_api/models/listing.rb', line 164

def save!(arguments={})
  writable_changed_keys = changed & WRITEABLE_FIELDS
  if writable_changed_keys.empty?
    SparkApi.logger.warn { "No supported listing change detected" }
  else
    results = connection.put "/flexmls#{self.class.path}/#{self.Id}", build_hash(writable_changed_keys), arguments
    @contstraints = []
    results.details.each do |detail|
      detail.each_pair do |k,v|
        v.each { |constraint| @constraints << Constraint.new(constraint)}
      end
    end
  end
  true
end

#shared_notes(fore = nil) ⇒ Object

‘fore’ is required when accessing an agent’s shared notes for a specific contact. If the ApiUser /is/ the contact, then it can be inferred by the api, so it’s unecessary



120
121
122
123
124
125
126
127
128
129
# File 'lib/spark_api/models/listing.rb', line 120

def shared_notes(fore=nil)
  Note.build_subclass.tap do |note|
    note.prefix = "/listings/#{self.ListingKey}"
    if fore.nil?
      note.element_name = "/shared/notes"
    else
      note.element_name = "/shared/notes/contacts/#{fore}"
    end
  end
end

#street_addressObject



131
132
133
# File 'lib/spark_api/models/listing.rb', line 131

def street_address        
  (self.UnparsedFirstLineAddress || '').delete(DATA_MASK).strip().gsub(/\s{2,}/, ' ')
end