Skip to content

Instantly share code, notes, and snippets.

@rentalcustard
Created November 23, 2011 16:25
Show Gist options
  • Save rentalcustard/1389123 to your computer and use it in GitHub Desktop.
Save rentalcustard/1389123 to your computer and use it in GitHub Desktop.
"model.show_on(view)" Not "view.show(model)"
#What follows is an extremely contrived example of how this might
# look. Please don't pay attention to the incredibly naive JSON
# and HTML creation code, that's not supposed to be the point.
class Account
def show_on(view)
view.show_balance(self.balance)
view.show_holder(self.holder_name)
view.show_creation_date(self.created_at)
end
end
class JSONAccountView
def initialize
@result = "{"
end
def show_balance(balance)
add_pair("balance", "£#{balance}")
end
def show_holder(holder)
add_pair("holder_name", holder)
end
def show_creation_date(date)
add_pair("created_on", date.to_s)
end
def finish(output)
output << (@result + "}")
end
private
def add_pair(label, value)
@result << "," unless @result == "{"
@result << "#{label}: #{value}"
end
end
class HTMLAccountView
def initialize
@result = "<html>" #and some other boilerplate...
end
def show_balance(balance)
add_pair("Balance", "£#{balance}")
end
def show_holder(holder)
add_pair("Account holder", holder)
end
def show_creation_date(date)
add_pair("Created at", date.format("some format string"))
end
def add_pair(label, value)
@result << "<span class=\"label\">#{label}</span>"
@result << '<span class="value">'
@result << value
@result << "</span>"
end
def finish(output)
output << (@result + closing_boilerplate_here)
end
end
class StreamingAccountView
def initialize
#set up stream
end
def show_balance(balance)
stream.send("bal: #{balance}")
end
def show_holder(holder)
stream.send("holder: #{holder}")
end
def show_creation_date(date)
stream.send("created: #{date}")
end
def finish
stream.close
end
end
account = Account.last
view = StreamingAccountView.new
account.show_on(view)
view.finish
account = Account.last
view = JSONAccountView.new #or HTML, same thing for our purposes
account.show_on(view)
view.finish(some_output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment