Revised from RBP Tip #8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# Thanks Fabian Streitel for pointing out that the previous # example does not allow setting name to nil or false # return @name if args @name = args end alias_method :name=, :name end # Works normally from the external interface person = Person person = "Gregory Brown" puts person # Looks nice from the inside as well: Person do name "Gregory Brown" puts name end # Without the optional argument to name(), we'd be stuck with: Person do self = "Gregory Brown" puts name end # Without the alias for name=, we'd be stuck with: person = Person person "Gregory Brown" puts person # You want to make sure to alias name= rather than just do attr_writer name, so as to not duplicate setter logic. # (unless you intentionally want to make them different) |

