Skip to content

Instantly share code, notes, and snippets.

@zuchmanski
Created January 25, 2014 16:29
Show Gist options
  • Save zuchmanski/8618967 to your computer and use it in GitHub Desktop.
Save zuchmanski/8618967 to your computer and use it in GitHub Desktop.
class DateTime
def to_db
strftime("%Y-%m-%d")
end
end
class Generator
class << self
attr_accessor :attributes, :number, :function_name, :children, :id
def set_number(n)
@number = n
end
def set_function_name(name)
@function_name = name
end
def attribute(name, type, &block)
@attributes ||= {}
@attributes[name] = { type: type, block: block }
end
def set_children(&block)
@children = block
end
def inc_id
@id ||= 0
@id += 1
end
end
def initialize(attrs = {})
@attrs = attrs
end
def output
"\n" + generate + children
end
def generate
out = []
@children_res = ""
@result = {}
self.class.number.times do
a = {}
id = self.class.inc_id
self.class.attributes.each do |name, values|
a[name] = escape(values[:block].call(@attrs.merge(:parent_id => self.class.id)), values[:type])
end
@children_res << self.class.children.call(@attrs.merge(:parent_id => self.class.id)) if self.class.children
out << a
@result[id] = a
end
format(out) + "\n"
end
def data
@result
end
def children
@children_res
end
def escape(value, type)
if value.nil?
return 'null'
else
case type
when :null
%{NULL}
when :string
if value == 'NULL'
%{NULL}
else
%{'#{value.gsub("'", "")}'}
end
when :integer
value.to_s
when :daterange
# '[2014-02-01, 2014-10-01)'
%{'[#{value.first.to_db}, #{value.last.to_db})'}
when :datetime
%{date '#{value.to_db}'}
end
end
end
def format(array)
array.map do |attributes|
"select #{self.class.function_name}(#{attributes.values.join(', ')});"
end.join("\n")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment