Created
November 28, 2009 22:40
-
-
Save mrrooijen/244681 to your computer and use it in GitHub Desktop.
This is an example of a Block-like Configuration Template.
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
# The BlockConfiguration Class for storing the root-level | |
# configuration attributes | |
class BlockConfiguration | |
attr_accessor :attributes | |
%w(attr1 attr2 attr3).each do |method| | |
define_method method do |value| | |
attributes[method] = value | |
end | |
end | |
def initialize | |
@attributes = Hash.new | |
@nested_config = NestedConfiguration.new | |
end | |
def nested_config(&block) | |
@nested_config.instance_eval(&block) | |
end | |
def get_nested_config | |
@nested_config | |
end | |
end | |
# The NestedConfiguration Class for Storing the Nested Attributes | |
# of the BlockConfiguration | |
class NestedConfiguration | |
attr_accessor :attributes | |
%w(attr1 attr2 attr3).each do |method| | |
define_method "nested_#{method}" do |value| | |
attributes["nested_#{method}"] = value | |
end | |
end | |
def initialize | |
@attributes = Hash.new | |
end | |
end | |
# The Block Config Method | |
def block_config(&block) | |
@block_config = BlockConfiguration.new | |
@block_config.instance_eval(&block) | |
end | |
# Configuration-like Block | |
block_config do | |
attr1 "This is Attribute 1" | |
attr2 "This is Attribute 2" | |
attr3 "This is Attribute 3" | |
# Nested Attributes | |
nested_config do | |
nested_attr1 "This is Nested Attribute 1" | |
nested_attr2 "This is Nested Attribute 2" | |
nested_attr3 "This is Nested Attribute 3" | |
end | |
end | |
# Output Examples | |
require "pp" | |
pp @block_config | |
pp @block_config.attributes | |
pp @block_config.attributes['attr1'] | |
pp @block_config.get_nested_config | |
pp @block_config.get_nested_config.attributes | |
pp @block_config.get_nested_config.attributes['nested_attr1'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment