Created
January 10, 2010 04:12
-
-
Save mxriverlynn/273328 to your computer and use it in GitHub Desktop.
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
module AttrMethods | |
class << Object | |
@@array_methods = {} | |
@@hash_methods = {} | |
def attr_array(*method_names) | |
@@array_methods[self] = method_names | |
end | |
def attr_hash(*method_names) | |
@@hash_methods[self] = method_names | |
end | |
end | |
def initialize | |
gen_array_methods(self, @@array_methods[self.class]) if @@array_methods.has_key?(self.class) | |
gen_hash_methods(self, @@hash_methods[self.class]) if @@hash_methods.has_key?(self.class) | |
super() | |
end | |
private | |
def gen_array_methods(obj, method_names) | |
method_names.each do |m| | |
obj.instance_eval(<<-EOF, __FILE__, __LINE__) | |
def #{m}(*args) | |
@#{m} = args | |
end | |
EOF | |
end | |
end | |
def gen_hash_methods(obj, method_names) | |
method_names.each do |m| | |
obj.instance_eval(<<-EOF, __FILE__, __LINE__) | |
def #{m}(*args) | |
@#{m} = *args | |
end | |
EOF | |
end | |
end | |
end |
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 MyClass | |
include AttrMethods | |
attr_array :my_method | |
attr_hash :method_two | |
def put_array | |
puts @my_method.join(" ") | |
end | |
def put_hash | |
@method_two.each do |k,v| | |
print "#{k} #{v} " | |
end | |
end | |
end |
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
foo = MyClass.new | |
foo.my_method "this", "is", "an", "array" | |
foo.put_array #=> this is an array | |
foo.method_two "this" => "hash", "was" => "created", "with" => "metaprogramming" | |
foo.put_hash #=> this hash was created with metaprogramming | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment