Skip to content

Instantly share code, notes, and snippets.

@pzol
Created May 30, 2012 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pzol/2837955 to your computer and use it in GitHub Desktop.
Save pzol/2837955 to your computer and use it in GitHub Desktop.
Reliable presenter code with monadic
class MonadicHotelBookingPresenter
def initialize(booking)
@booking = Maybe(booking)
end
def hotel_name
hotel_details['name'].fetch.to_s
end
def hotel_category
hotel_details['category'].fetch(0)
end
def consumer_price
prices.detect { |p| p['type'] == 'CONSUMER' }.or({ 'currency' => 'YYY', 'value' => 0.0 }).fetch
end
private
def hotel
services.map {|e| e.detect { |svc| svc['product'] == 'HOTEL' } }
end
def hotel_details
hotel['details']
end
def prices
@booking['prices']
end
def services
@booking['services']
end
end
class HotelBookingPresenter
def initialize(booking)
@booking = booking
end
def hotel_name
hotel_details.fetch('name', 'Nothing')
end
def hotel_category
hotel_details.fetch('category', 0)
end
def consumer_price
prices.detect { |p| p['type'] == 'CONSUMER' } || { 'currency' => 'YYY', 'value' => 0.0 }
end
private
def hotel
services.detect { |svc| svc['product'] == 'HOTEL' } || {}
end
def hotel_details
hotel.fetch('details', {})
end
def prices
@booking.fetch('prices', [])
end
def services
@booking.fetch('services', [])
end
end
require 'monadic'
require './monadic'
require './original'
shared_examples 'presenter' do
describe 'for an empty booking' do
subject { presenter.new({}) }
its(:hotel_name) { should == 'Nothing' }
its(:hotel_category) { should == 0 }
its(:consumer_price) { should == {'currency' => 'YYY', 'value' => 0.0 } }
end
describe 'for a complete booking' do
let(:booking) do
{
"prices" => [
{
"type" => "CONSUMER",
"currency" => "EUR",
"value" => 119.78
}
],
"services" => [
{
"product" => "HOTEL",
"details" => {
"name" => "Hotel Wroclaw",
"category" => 3
}
}
]
}
end
subject { presenter.new(booking) }
its(:hotel_name) { should == 'Hotel Wroclaw' }
its(:hotel_category) { should == 3 }
end
end
describe MonadicHotelBookingPresenter do
it_behaves_like 'presenter' do
let(:presenter) { MonadicHotelBookingPresenter }
end
end
describe HotelBookingPresenter do
it_behaves_like 'presenter' do
let(:presenter) { HotelBookingPresenter }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment