Class: Sequel::Schema::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/sequel/schema/schema_generator.rb

Instance Method Summary collapse

Constructor Details

#initialize(db, table_name, &block) ⇒ Generator

Returns a new instance of Generator.



4
5
6
7
8
9
10
11
# File 'lib/sequel/schema/schema_generator.rb', line 4

def initialize(db, table_name, &block)
  @db = db
  @table_name = table_name
  @columns = []
  @indexes = []
  @primary_key = nil
  instance_eval(&block)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(type, name = nil, opts = nil) ⇒ Object



13
14
15
# File 'lib/sequel/schema/schema_generator.rb', line 13

def method_missing(type, name = nil, opts = nil)
  name ? column(name, type, opts) : super
end

Instance Method Details

#column(name, type, opts = nil) ⇒ Object



36
37
38
# File 'lib/sequel/schema/schema_generator.rb', line 36

def column(name, type, opts = nil)
  @columns << {:name => name, :type => type}.merge(opts || {})
end

#create_infoObject



54
55
56
57
58
59
# File 'lib/sequel/schema/schema_generator.rb', line 54

def create_info
  if @primary_key && !has_column?(@primary_key[:name])
    @columns.unshift(@primary_key)
  end
  [@table_name, @columns, @indexes]
end

#foreign_key(name, opts = nil) ⇒ Object



40
41
42
# File 'lib/sequel/schema/schema_generator.rb', line 40

def foreign_key(name, opts = nil)
  @columns << {:name => name, :type => :integer}.merge(opts || {})
end

#has_column?(name) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
47
# File 'lib/sequel/schema/schema_generator.rb', line 44

def has_column?(name)
  @columns.each {|c| return true if c[:name] == name}
  false
end

#index(columns, opts = nil) ⇒ Object



49
50
51
52
# File 'lib/sequel/schema/schema_generator.rb', line 49

def index(columns, opts = nil)
  columns = [columns] unless columns.is_a?(Array)
  @indexes << {:columns => columns}.merge(opts || {})
end

#primary_key(name, *args) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/sequel/schema/schema_generator.rb', line 21

def primary_key(name, *args)
  @primary_key = @db.serial_primary_key_options.merge({
    :name => name
  })
  
  if opts = args.pop
    opts = {:type => opts} unless opts.is_a?(Hash)
    if type = args.pop
      opts.merge!(:type => type)
    end
    @primary_key.merge!(opts)
  end
  @primary_key
end

#primary_key_nameObject



17
18
19
# File 'lib/sequel/schema/schema_generator.rb', line 17

def primary_key_name
  @primary_key ? @primary_key[:name] : nil
end