2

我试图了解 Sequel 的工作原理。下面的示例继承自 Sequel::Model 并调用 set_schema、create_table 等。

我试图找到这些方法的文档,但在 Sequel::Model 的 rdoc 上没有运气:http: //sequel.rubyforge.org/rdoc/classes/Sequel/Model.html

这些方法从何而来,Sequel::Model 如何使它们可用?

class Task < Sequel::Model
  set_schema do
    primary_key :id

    varchar :title, :unique => true, :empty => false
    boolean :done, :default => false
  end

  create_table unless table_exists?

  if empty?
    create :title => 'Laundry'
    create :title => 'Wash dishes'
  end
end
4

1 回答 1

3

它们在Sequel::Plugins::Schema::ClassMethods(lib/sequel/plugins/schema.rb) 中定义,并在您调用plugin :schema模型时包含在内。

http://sequel.rubyforge.org/rdoc-plugins/classes/Sequel/Plugins/Schema/ClassMethods.html#M000110

http://sequel.rubyforge.org/rdoc/classes/Sequel/Model.html#M000130

plugin :schema问题中的示例不完整,除非设置了与数据库的连接并从模型中调用,否则该示例将不起作用。

 irb(main):001:0> require "rubygems"
 => true
 irb(main):002:0> require "sequel"
 => true
 irb(main):003:0> 
 irb(main):004:0*   # connect to an in-memory database
 irb(main):005:0*   DB = Sequel.sqlite
 => #<Sequel::SQLite::Database: "sqlite:/">
 irb(main):006:0> class Task < Sequel::Model
 irb(main):007:1>     set_schema do
 irb(main):008:2*           primary_key :id
 irb(main):009:2>     
 irb(main):010:2*           varchar :title, :unique => true, :empty => false
 irb(main):011:2>         boolean :done, :default => false
 irb(main):012:2>       end
 irb(main):013:1>   
 irb(main):014:1*       create_table unless table_exists?
 irb(main):015:1>   
 irb(main):016:1*       if empty?
 irb(main):017:2>         create :title => 'Laundry'
 irb(main):018:2>         create :title => 'Wash dishes'
 irb(main):019:2>       end
 irb(main):020:1>   end
 NoMethodError: undefined method `set_schema' for Task:Class
   from (irb):7
 irb(main):021:0> class Task < Sequel::Model
 irb(main):022:1>   plugin :schema
 irb(main):023:1>     set_schema do
 irb(main):024:2*           primary_key :id
 irb(main):025:2>     
 irb(main):026:2*           varchar :title, :unique => true, :empty => false
 irb(main):027:2>         boolean :done, :default => false
 irb(main):028:2>       end
 irb(main):029:1>   
 irb(main):030:1*       create_table unless table_exists?
 irb(main):031:1>   
 irb(main):032:1*       if empty?
 irb(main):033:2>         create :title => 'Laundry'
 irb(main):034:2>         create :title => 'Wash dishes'
 irb(main):035:2>       end
 irb(main):036:1>   end
 => #<Task @values={:title=>"Wash dishes", :done=>false, :id=>2}>
 irb(main):037:0> 
于 2009-11-25T06:47:50.883 回答