Class: Roomer::Tools

Inherits:
Object
  • Object
show all
Defined in:
lib/roomer/tools.rb

Class Method Summary (collapse)

Class Method Details

+ (Object) create_schema(schema_name)

Creates a schema in PostgreSQL

Parameters:

  • schema_name (#to_s)

    declaring the name of the schema



7
8
9
# File 'lib/roomer/tools.rb', line 7

def create_schema(schema_name)
  ActiveRecord::Base.connection.execute "CREATE SCHEMA #{schema_name.to_s}"
end

+ (Object) drop_schema(schema_name)

Drops a schema and all it’s objects (Cascades)

Parameters:

  • schema_name (#to_s)

    declaring the name of the schema to drop



13
14
15
# File 'lib/roomer/tools.rb', line 13

def drop_schema(schema_name)
  ActiveRecord::Base.connection.execute("DROP SCHEMA IF EXISTS #{name.to_s} CASCADE")
end

+ (Object) ensure_prefix(prefix, &block)

Note:

All the Models will have the same prefix, caution is advised

Ensures the same ActiveRecord::Base#table_name_prefix for all the models executed in the block

Examples:

ensure_prefix(:global) do
   Person.find(1)  # => will execute "SELECT id FROM 'global.person'"
end

Parameters:

  • A (#to_s)

    Symbol declaring the table name prefix

  • code (#call)

    to execute



52
53
54
55
56
# File 'lib/roomer/tools.rb', line 52

def ensure_prefix(prefix, &block)
  ActiveRecord::Base.table_name_prefix = "#{prefix.to_s}#{Roomer.schema_seperator}"
  yield
  ActiveRecord::Base.table_name_prefix = old_prefix
end

+ (Object) ensure_schema_migrations

Ensures schema_migrations table exists and creates otherwise

See Also:

  • ActiveRecord::Base.connection#initialize_schema_migrations_table


60
61
62
# File 'lib/roomer/tools.rb', line 60

def ensure_schema_migrations
  ActiveRecord::Base.connection.initialize_schema_migrations_table
end

+ (Object) ensuring_schema(schema_name, &block)

Ensures the schema and schema_migrations exist(creates them otherwise) and executes the code block

Examples:

ensuring_schema(:global) do
   ActiveRecord::Migrator.migrate('/db/migrate', '20110812012536')
end

Parameters:

  • schema_name (#to_s)

    declaring name to ensure

  • &block (#call)

    code to execute

Raises:

  • (ArgumentError)


31
32
33
34
35
36
37
38
39
40
# File 'lib/roomer/tools.rb', line 31

def ensuring_schema(schema_name, &block)
  raise ArgumentError.new("schema_name not present") unless schema_name
  ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
  create_schema(schema_name) unless schemas.include?(schema_name.to_s)
  ActiveRecord::Base.table_name_prefix = "#{schema_name.to_s}#{Roomer.schema_seperator.to_s}"
  ensure_prefix(schema_name) do
    ensure_schema_migrations
    yield
  end
end

+ (Array) schemas

lists the schemas available

Returns:

  • (Array)

    list of schemas



19
20
21
# File 'lib/roomer/tools.rb', line 19

def schemas
  ActiveRecord::Base.connection.query("SELECT nspname FROM pg_namespace WHERE nspname !~ '^pg_.*'").flatten
end