Skip to content

Instantly share code, notes, and snippets.

@gupta-ankit
Last active August 7, 2022 14:28
Show Gist options
  • Save gupta-ankit/8868300906979d34a9fee164140435f4 to your computer and use it in GitHub Desktop.
Save gupta-ankit/8868300906979d34a9fee164140435f4 to your computer and use it in GitHub Desktop.
Showing presenter pattern with simple ruby code
revenues = {
2018 => 100000,
2019 => 10000,
2020 => 1000,
2021 => 5000
}
class Financials
attr_reader :revenues, :country
def initialize(country:,revenues:)
@country = country
@revenues = revenues
end
def revenue_growths
growths = {}
revenues.each_with_index do |(year, revenue), i|
if i==0
growths[year] = nil
else
growths[year] = (revenue - revenues[year-1])/revenues[year-1].to_f
end
end
growths
end
end
class FinancialsPresenter
def initialize(financials)
@financials = financials
end
def revenues
@financials.revenues.map { |year, revenue|
[year, "#{currency}#{@financials.revenues[year]/1000}K"]
}.to_h
end
def revenue_growths
@financials.revenue_growths.map { |year, growth|
[year, (growth.nil? ? "N/A" : "#{growth * 100}%")]
}.to_h
end
private
def currency
case @financials.country
when "UK", "GB"
"€"
when "US"
"$"
end
end
end
def show_report(revenues)
f = Financials.new(country: "US", revenues: revenues)
puts "year\trevenue\trevenue_growths"
f.revenues.each do |year, revenue|
puts "#{year}\t#{revenue}\t#{f.revenue_growths[year]}"
end
end
def show_report2(revenues)
f = Financials.new(country: "UK", revenues: revenues)
puts "year\trevenue\trevenue_growths"
currency_symbol = case f.country
when "US"
"$"
when "GB", "UK"
"€"
end
f.revenues.each do |year, revenue|
revenue_k = "#{revenue/1000}K"
growth = if f.revenue_growths[year].nil?
"N/A"
else
"#{f.revenue_growths[year] * 100}%"
end
puts "#{year}\t#{currency_symbol}#{revenue_k}\t#{growth}"
end
end
def show_report3(revenues)
f = FinancialsPresenter.new(Financials.new(country: "UK", revenues: revenues))
puts "year\trevenue\trevenue_growths"
f.revenues.each do |year, revenue|
puts "#{year}\t#{revenue}\t#{f.revenue_growths[year]}"
end
end
show_report(revenues)
show_report2(revenues)
show_report3(revenues)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment