Created
July 9, 2012 14:04
-
-
Save jeremyf/3076768 to your computer and use it in GitHub Desktop.
Overwrite Ruby's #to_s method for cleaning up views.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# By making use of Ruby's natural coercion methods (i.e. #to_s, #to_i) | |
# we can save some headaches with potential nil objects. | |
# By overwriting the #to_s method on a class, we can get a lot of benefits | |
# in our presentation logic. We don't have to remember are we using #title | |
# or #pretty_title. | |
# I would caution that we not put markup in the #to_s method, as that violates | |
# the intent of #to_s. In fact, markup should probably not be in the model, | |
# as the markup makes an assumption about how the content is presented. | |
# If an object can be known by different names, then the #to_s method may not | |
# work. However, I would challenge us to ask why an object is known by different | |
# names and consider refactoring that object. | |
class Person | |
attr_accessor :name | |
end | |
class Place | |
attr_accessor :name | |
def to_s | |
"#{name}" | |
end | |
end | |
@person = Person.new | |
@person.name = "Jeremy Friesen" | |
@place = Place.new | |
@place.name = "Hesburgh Library" | |
puts @person | |
# => "#<Person:0x107a3d9e8>" | |
puts @place | |
# => "Hesburgh Library" | |
puts "Hello #{@person}, you are at #{@place}" | |
# => "Hello #<Person:0x107a3d9e8>, you are at Hesburgh Library" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment