module InactiveRecord
class Base
def initialize(&block)
@attrs = {}
end
def method_missing(method, *args, &block)
attr = method.to_s
if attr =~ /=$/
@attrs[attr.chop] = args[0]
else
@attrs[attr]
end
end
def save
p @attrs
end
end
end
更进一步,对于下边这种形式的创建方式:
1234567
juntao = Person.new do |p|
p.name = 'Juntao'
p.age = 28
p.email = 'juntao.qiu@gmail.com'
end
juntao.save
则需要对InactiveRecord::Base中做一些修改:
12345678
def initialize(&block)
@attrs = {}
if block_given?
if block.arity == 1
yield self
end
end
end
require 'spec_helper'
InactiveRecord::Base.config do |config|
config.schemas "spec/fixtures/schema.yml"
end
class Person < InactiveRecord::Base
end
describe "InactiveRecord" do
context "save attribtues" do
subject {
juntao = Person.new do |p|
p.name = 'juntao'
p.age = 28
p.email = 'juntao.qiu@gmail.com'
end
juntao
}
it "should read saved attributes " do
subject.name.should == 'juntao'
subject.age.should == 28
subject.email.should == "juntao.qiu@gmail.com"
end
end
context "schema validation" do
subject {
juntao = Person.new do |p|
p.name = 'juntao'
p.age = 28
p.email = 'juntao.qiu@gmail.com'
end
juntao
}
context "change a valid field" do
it "should succeed" do
subject.age = 29
subject.age.should == 29
end
end
context "change a invalid field" do
it "should raise error" do
expect { subject.weight= 60 }.to raise_error(StandardError)
end
end
end
end
def inherited(who)
table_name = who.name.downcase
table = YAML.load_file("./metadata/#{table_name}.yml")
who.class_eval do
define_method :schema do
table[who.name]
end
end
end