Created
November 16, 2010 08:43
-
-
Save nicolaracco/701594 to your computer and use it in GitHub Desktop.
Demo of ruby dynamic method/variable creation
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
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