Skip to content

Instantly share code, notes, and snippets.

@drKreso
Created March 25, 2012 20:30
Show Gist options
  • Save drKreso/2199562 to your computer and use it in GitHub Desktop.
Save drKreso/2199562 to your computer and use it in GitHub Desktop.
MultidimensionalTable
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
@drKreso
Copy link
Author

drKreso commented Mar 25, 2012

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment