From dd507e3cbfd396b3a17eb36e03e970ea18d03f84 Mon Sep 17 00:00:00 2001 From: Akinori MUSHA Date: Fri, 19 Sep 2014 21:57:45 +0900 Subject: [PATCH] Make Event's location accessible from Liquid templates. --- app/models/event.rb | 4 ++++ lib/location.rb | 14 ++++++++++++++ spec/lib/location_spec.rb | 12 ++++++++++++ spec/models/event_spec.rb | 7 +++++++ 4 files changed, 37 insertions(+) diff --git a/app/models/event.rb b/app/models/event.rb index a0a83c3f..321fc233 100644 --- a/app/models/event.rb +++ b/app/models/event.rb @@ -117,4 +117,8 @@ class EventDrop @object.created_at } end + + def _location_ + @object.location + end end diff --git a/lib/location.rb b/lib/location.rb index 6f7a6634..54b7b7b4 100644 --- a/lib/location.rb +++ b/lib/location.rb @@ -1,6 +1,10 @@ +require 'liquid' + Location = Struct.new(:lat, :lng, :radius, :speed, :course) class Location + include LiquidDroppable + protected :[]= def initialize(data = {}) @@ -86,3 +90,13 @@ class Location end end end + +class LocationDrop + KEYS = Location.members.map(&:to_s).concat(%w[latitude longitude]) + + def before_method(key) + if KEYS.include?(key) + @object.__send__(key) + end + end +end diff --git a/spec/lib/location_spec.rb b/spec/lib/location_spec.rb index 9718a343..749f350a 100644 --- a/spec/lib/location_spec.rb +++ b/spec/lib/location_spec.rb @@ -53,4 +53,16 @@ describe Location do expect(Location.new(lat: 2, radius: 1).present?).to be_falsy expect(Location.new(lng: 3, radius: 1).present?).to be_falsy end + + it "is droppable" do + { + '{{location.lat}}' => '2.0', + '{{location.latitude}}' => '2.0', + '{{location.lng}}' => '3.0', + '{{location.longitude}}' => '3.0', + }.each { |template, result| + expect(Liquid::Template.parse(template).render('location' => location.to_liquid)).to eq(result), + "expected #{template.inspect} to expand to #{result.inspect}" + } + end end diff --git a/spec/models/event_spec.rb b/spec/models/event_spec.rb index a233fa4a..e7fd4bb8 100644 --- a/spec/models/event_spec.rb +++ b/spec/models/event_spec.rb @@ -174,6 +174,8 @@ describe EventDrop do 'title' => 'some title', 'url' => 'http://some.site.example.org/', } + @event.lat = 2 + @event.lng = 3 @event.save! end @@ -210,4 +212,9 @@ describe EventDrop do t = '{{created_at | date:"%FT%T%z" }}' interpolate(t, @event).should eq(@event.created_at.strftime("%FT%T%z")) end + + it 'should have _location_' do + t = '{{_location_.lat}},{{_location_.lng}}' + interpolate(t, @event).should eq("2.0,3.0") + end end