Add Event#location.

This commit is contained in:
Akinori MUSHA 2014-09-19 10:36:27 +09:00
parent aceed9ac83
commit d4bd3c7c8b
2 changed files with 82 additions and 0 deletions

View file

@ -32,6 +32,38 @@ class Event < ActiveRecord::Base
where.not(lat: nil).where.not(lng: nil)
}
def location
@location ||= {
# lat and lng are BigDecimal, so convert them to Float
lat: (lat.to_f if lat),
lng: (lng.to_f if lng),
radius:
begin
h = payload[:horizontal_accuracy].presence
v = payload[:vertical_accuracy].presence
if h && v
(h.to_f + v.to_f) / 2
else
(h || v || payload[:accuracy]).to_f
end
end,
course:
begin
if (v = payload[:course].presence) &&
(v = v.to_f) >= 0
v
end
end,
speed:
begin
if (v = payload[:speed].presence) &&
(v = v.to_f) >= 0
v
end
end,
}
end
# Emit this event again, as a new Event.
def reemit!
agent.create_event :payload => payload, :lat => lat, :lng => lng

View file

@ -15,6 +15,56 @@ describe Event do
end
end
describe "#location" do
it "returns a default hash when an event does not have a location" do
event = events(:bob_website_agent_event)
event.location.should == {
lat: nil,
lng: nil,
radius: 0.0,
speed: nil,
course: nil,
}
end
it "returns a hash containing location information" do
event = events(:bob_website_agent_event)
event.lat = 2
event.lng = 3
event.payload = {
radius: 300,
speed: 0.5,
course: 90.0,
}
event.save!
event.location.should == {
lat: 2.0,
lng: 3.0,
radius: 0.0,
speed: 0.5,
course: 90.0,
}
end
it "ignores invalid speed and course" do
event = events(:bob_website_agent_event)
event.lat = 2
event.lng = 3
event.payload = {
speed: -1,
course: -1,
}
event.save!
event.location.should == {
lat: 2.0,
lng: 3.0,
radius: 0.0,
speed: nil,
course: nil,
}
end
end
describe "#reemit" do
it "creates a new event identical to itself" do
events(:bob_website_agent_event).lat = 2