module LookupBy::Lookup::SchemaMethods

Public Instance Methods

create_lookup_table(name, options = {}) { |t| ... } click to toggle source

Create a lookup table.

@example

create_lookup_table :statuses, schema: "custom", small: true

create_lookup_table :companies do |t|
  t.string :short_name
end

@param [Symbol] name @param [Hash] options @option options [Symbol] lookup_column Name of the lookup column. @option options [Symbol] lookup_type Type of the lookup column, _e.g. :text, :uuid, or :inet_. @option options [String] primary_key Name of the primary key. @option options [String] schema

# File lib/lookup_by/lookup.rb, line 161
def create_lookup_table(name, options = {})
  options.symbolize_keys!

  schema = options[:schema].to_s

  if schema.present?
    table = name.to_s
  else
    schema, table = name.to_s.split('.')
    schema, table = nil, schema unless table
  end

  name = schema.blank? ? table : "#{schema}.#{table}"

  lookup_column = options[:lookup_column] || table.singularize
  lookup_type   = options[:lookup_type]   || :text

  table_options = options.slice(:primary_key, :id)
  table_options[:primary_key] ||= table.singularize + '_id'

  table_options[:id] = false if options[:small]

  create_table name, table_options do |t|
    t.column table_options[:primary_key], 'smallserial primary key' if options[:small]

    t.column lookup_column, lookup_type, null: false

    yield t if block_given?
  end

  add_index name, lookup_column, unique: true, name: "#{table}__u_#{lookup_column}"
end
create_lookup_tables(*names) click to toggle source
# File lib/lookup_by/lookup.rb, line 194
def create_lookup_tables(*names)
  options = names.last.is_a?(Hash) ? names.pop : {}

  names.each do |name|
    create_lookup_table name, options
  end
end