Created
August 20, 2013 20:54
-
-
Save the-undefined/6287170 to your computer and use it in GitHub Desktop.
Take advantage of metaprogramming and avoid littering the logic of your code with `define_method` declarations.
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 Cappy | |
def attr_capcessor attr | |
attr_reader attr.to_sym | |
define_method "#{attr}=" do |value| | |
instance_variable_set("@#{attr}", value.to_s.upcase) | |
end | |
end | |
end | |
class A | |
extend Cappy | |
attr_capcessor :body | |
end | |
a = A.new | |
lower_case_val = "wants to be uppcased" | |
a.body = lower_case_val | |
STDERR.puts "SAVED: #{lower_case_val}" | |
STDERR.puts "Retrieved: #{a.body}" | |
# OUTPUT | |
# | |
# $ ruby attr_capcessor.rb | |
# | |
# SAVED: wants to be uppcased | |
# Retrieved: WANTS TO BE UPPCASED |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment