-
Book Overview & Buying
-
Table Of Contents
Polished Ruby Programming - Second Edition
By :
One of the best reasons to use metaprogramming is to eliminate redundancy. No Ruby programmer wants to write the same or similar code over and over, unless they are getting paid by the line. Imagine programming in Ruby without attr_accessor:
class Foo
def bar = @bar
def bar=(v)
@bar = v
end
def baz = @baz
def baz=(v)
@baz = v
end
end
It would suck to have to define accessor methods this verbosely, even when you can use endless methods. Ruby realizes that no programmer likes this sort of repetitive coding, and being designed around programmer happiness, Ruby includes attr_accessor and similar methods:
class Foo
attr_accessor :bar, :baz
end
Pretty much anytime you see yourself writing repetitive methods, see whether there is a way you can eliminate the redundancy via metaprogramming. Assume you are storing data for a class in a hash:
class FooStruct
def initialize(**kwargs) = @values = kwargs
And you have accessors using that hash:
def bar...
Change the font size
Change margin width
Change background colour