Skip to content

Instantly share code, notes, and snippets.

@pmoghaddam
Created May 16, 2015 06:48
Show Gist options
  • Save pmoghaddam/07fe8a6ff1af11505df3 to your computer and use it in GitHub Desktop.
Save pmoghaddam/07fe8a6ff1af11505df3 to your computer and use it in GitHub Desktop.
Sample Metaprogramming
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
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