Created
September 11, 2015 20:22
-
-
Save rvalenciano/67488889956e1d8fa306 to your computer and use it in GitHub Desktop.
Custom attr_accessor
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
class SuperFoo | |
attr_accessor :data | |
def initialize | |
@data = {} | |
end | |
def self.data_accessor(*args) | |
args.each do |arg| | |
define_method("#{arg}=") do |val| | |
@data[arg] = val | |
#instance_variable_set("@#{arg}", val) | |
end | |
define_method("#{arg}") do | |
@data[arg] | |
#instance_variable_get("@#{arg}") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Description
Some time ago, you wrote the class SuperFoo. It has only one attribute, data, which is initialized as a hash:
Naturally, you put things into the hash from time to time:
But then you got tired of typing hash things, and made some getters and setters to make accessing data easier.
That was nice for a while. But now, you have been tasked with making literally dozens of classes that inherit from SuperFoo, each of which will have their own unique variables that will be stored in the data hash. You shudder at the thought of writing your getter and setter methods over and over again, especially because you hate repeating code.
You figure there has to be a way to dynamically generate these methods...
Well, there is!
In this kata, you must write a class-level method called data_accessor. It will define your "data getters and setters" for all names you pass to it.
Basically, you are defining a custom attr_accessor method, which will let you do this:
Test Cases