module ActiveRecord
class Base
def self.method_missing_with_examples(method, *args, &blk)
@custom_examples ||= {}

if match = method.to_s.match(/(\w*)_example/)
if block_given?
@custom_examples[match[0]] = blk
elsif @custom_examples[match[0]]
blk = @custom_examples[match[0]]
input = blk.call(*args)
if args[0].is_a?(Hash)
input.merge!(args[0])
end

self.create!(input)
else
method_missing_without_examples(method, args, &blk)
end
else
method_missing_without_examples(method, args, &blk)
end
end
class << self
alias method_missing_without_examples method_missing
alias method_missing method_missing_with_examples
end

def self.example(klass_name={}, attributes={})
if klass_name.is_a? Symbol
klass = Object.const_get(klass_name.to_s.camelize)
klass.example({:full => @full}.merge(attributes))
else
attributes = klass_name

@full = attributes.delete(:full)
save = attributes.delete(:save)

if @minimum_example_blk
values = @minimum_example_blk.call(attributes)
attributes = values.merge(attributes) if values.is_a?(Hash)
end

obj = self.new(attributes)
obj.save! unless save === false

if @full && @optional_example_blk
values = @optional_example_blk.call(obj)
obj.update_attributes(values.merge(attributes)) if values.is_a?(Hash)
end

return obj
end
end

def self.minimum_example(args={}, &blk)
if blk
@minimum_example_blk = blk
else
@minimum_example_blk = Proc.new { args }
end
end
def self.optional_example(args={}, &blk)
if blk
@optional_example_blk = blk
else
@optional_example_blk = Proc.new { args }
end
end
end
end