3 ms·
There's more than one way to write the corresponding Ruby snippet. If I had been writing it, I might have translated it something like this: class BlogPost
by jez 4y ago
There's more than one way to write the corresponding Ruby snippet. If I had been writing it, I might have translated it something like this:
class BlogPost
class << self
attr_accessor :count
end
self.count = 0
attr_accessor :title, :body
def initialize(title, body)
@title = title
@body = body
@published = false
BlogPost.count += 1
end
def publish!
@published = true
end
def to_s = @title
def count = self.class.count
end
This avoids needing to understand what `@@count` means, and lets you use the same syntax as in python: `BlogPost.count += 1`.
Or, if I were in a codebase using static type annotations with Sorbet, I'd do something like this[0]. To each their own, write code in the language and style that makes the most sense to you.
[0] https://sorbet.run/#%23%20typed%3A%20true%0Aclass%20Module%3B%20include%20T%3A%3ASig%3B%20end%0A%0Aclass%20BlogPost%20%3C%20T%3A%3AStruct%0A%20%20class%20%3C%3C%20self%0A%20%20%20%20sig%20%7Breturns%28Integer%29%7D%0A%20%20%20%20attr_accessor%20%3Acount%0A%20%20end%0A%0A%20%20prop%20%3Atitle%2C%20String%0A%20%20prop%20%3Abody%2C%20String%0A%20%20prop%20%3Apublished%2C%20T%3A%3ABoolean%2C%20default%3A%20false%0A%0A%20%20def%20initialize%28title%3A%2C%20body%3A%2C%20published%3A%20false%29%0A%20%20%20%20super%0A%20%20%20%20BlogPost.count%20%2B%3D%201%0A%20%20end%0A%0A%20%20def%20publish!%0A%20%20%20%20%40published%20%3D%20true%0A%20%20end%0A%0A%20%20def%20to_s%20%3D%20title%0A%20%20def%20count%20%3D%20self.class.count%0Aend https://sorbet.run/#%23%20typed%3A%20true%0Aclass%20Module%3...
- gmalette 4y agoThat’s without even mentioning the footguns available in @@count Jez!
- jez 4y agoAh sure, this alternate implementation assumes that the BlogPost class is final and never subclassed. If you plan to subclass BlogPost, the translation is not identical, as the alternate implementation would not keep track of a global count of posts across all subclasses, only of `BlogPost` instances exactly.