Created
June 9, 2013 08:11
-
-
Save khacanh/5742767 to your computer and use it in GitHub Desktop.
My simple and erring dynamic method generation
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 MyAttributes | |
def self.included base | |
base.extend ClassMethods | |
base.send :include, InstanceMethods | |
end | |
module ClassMethods | |
def has_attributes attrs | |
attrs.each do |attr| | |
attr = attr.to_s | |
generate_getter attr | |
generate_setter attr | |
end | |
end | |
def generate_getter attr | |
class_eval do | |
define_method attr do | |
read_attribute attr | |
end | |
end | |
end | |
def generate_setter attr | |
class_eval do | |
define_method "#{attr}=" do |value| | |
write_attribute attr, value | |
end | |
end | |
end | |
end | |
module InstanceMethods | |
attr_reader :attributes | |
def method_missing method, *args, &block | |
super | |
end | |
def write_attribute(attr, value) | |
@attributes ||= {} | |
@attributes[attr] = value | |
end | |
def read_attribute(attr) | |
@attributes[attr] if @attributes | |
end | |
private | |
end | |
end | |
class Klass | |
include MyAttributes | |
has_attributes ["name", "age"] | |
end | |
k = Klass.new | |
k.name = "My Name" | |
k.name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment