Created
March 25, 2012 20:30
-
-
Save drKreso/2199562 to your computer and use it in GitHub Desktop.
MultidimensionalTable
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 MultidimensionalTable | |
def initialize | |
set_dimensions(dimensions) | |
data | |
end | |
def set_dimensions(map) | |
@dimensions = map | |
@dimensions.each do |key, value| | |
value.each do |possible_value| | |
Kernel.class_eval do | |
define_method possible_value do |value = nil, &block| | |
if value.nil? && !block.nil? | |
@index_level += 1 | |
@context[@index_level] = "@attributes[:#{key}] == :#{possible_value}" | |
block.call | |
@index_level -= 1 | |
elsif !value.nil? | |
context = (1..@index_level).reduce([]) { |context, level| context << @context[level] } | |
@table_rules[value] = context << ["@attributes[:#{key}] == :#{possible_value}"] | |
end | |
end | |
end | |
end | |
end | |
end | |
def update_attributes(attrs) | |
attrs.each do |key, value| @attributes[key] = value end | |
end | |
def table_result | |
@table_rules.each { |key, condition| return key if eval(condition.join(' && ')) == true } | |
end | |
def table_data | |
@context = [] | |
@table_rules = {} | |
@attributes ||= {} | |
@index_level = 0 | |
yield | |
end | |
def dimensions | |
@dimensions ||= {} | |
end | |
end | |
class TestClass | |
include MultidimensionalTable | |
def dimensions | |
{ | |
:test_material => [:test_potassium, :coal, :sugar] , | |
:time_of_day => [:morning, :evening], | |
:part_of_world => [:first_world, :third_world] | |
} | |
end | |
def data | |
table_data do | |
morning do | |
first_world do | |
coal '8t' | |
sugar '9t' | |
end | |
end | |
end | |
end | |
end | |
puts TestClass.new.tap { |test| test.update_attributes(:test_material => :coal, :time_of_day => :morning, :part_of_world => :first_world ) }.table_result | |
puts TestClass.new.tap { |test| test.update_attributes(:test_material => :sugar, :time_of_day => :morning, :part_of_world => :first_world ) }.table_result | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This set_dimension is bothering me in a sense that I keep track of current contex and have to count level on which I am on.