Created
May 16, 2015 06:48
-
-
Save pmoghaddam/07fe8a6ff1af11505df3 to your computer and use it in GitHub Desktop.
Sample Metaprogramming
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 ConfigAccessor | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
# Assumes config will be accessible like an attribute | |
def config_accessor(config, attr) | |
# Define reader | |
define_method(attr) do | |
self.public_send(config)[attr] | |
end | |
# Define writer | |
define_method("#{attr}=") do |v| | |
self.public_send(config)[attr] = v | |
end | |
end | |
end | |
end |
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
class Example | |
include ConfigAccessor | |
attr_accessible :sample_config | |
# Utilize the accessor provided by ConfigAccessor | |
config_accessor :sample_config, :port | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment