Skip to content

Instantly share code, notes, and snippets.

@the-undefined
Created August 20, 2013 20:54
Show Gist options
  • Save the-undefined/6287170 to your computer and use it in GitHub Desktop.
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.
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