Skip to content

Instantly share code, notes, and snippets.

@nicolaracco
Created November 16, 2010 08:43
Show Gist options
  • Save nicolaracco/701594 to your computer and use it in GitHub Desktop.
Save nicolaracco/701594 to your computer and use it in GitHub Desktop.
Demo of ruby dynamic method/variable creation
require 'rubygems'
require 'active_support'
# Include this module to define additional helpers
module MyAccessors
extend ActiveSupport::Concern
module ClassMethods
# This helper creates accessors
def create_my_accessors *names
names.each do |method| # for each defined method
define_method method do
self.instance_variable_get("@#{method}") # return @method
end
define_method "#{method}=" do |val|
self.instance_variable_set("@#{method}", val) # @method = val
end
end
end
end
end
class MyObject
include MyAccessors
create_my_accessors :title, :desc
end
my = MyObject.new
my.title = "MyTitle"
my.desc = "MyDescription"
puts "Title: #{my.title}"
puts "Desc: #{my.desc}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment