Module: Torque::PostgreSQL::Attributes::Builder

Defined in:
lib/torque/postgresql/attributes/builder.rb,
lib/torque/postgresql/attributes/builder/enum.rb,
lib/torque/postgresql/attributes/builder/period.rb,
lib/torque/postgresql/attributes/builder/full_text_search.rb

Defined Under Namespace

Classes: Enum, FullTextSearch, Period

Class Method Summary collapse

Class Method Details

.include_on(klass, method_name, builder_klass, **extra, &block) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/torque/postgresql/attributes/builder.rb', line 11

def self.include_on(klass, method_name, builder_klass, **extra, &block)
  klass.define_singleton_method(method_name) do |*args, **options|
    return unless table_exists?

    args.each do |attribute|
      # Generate methods on self class
      builder = builder_klass.new(self, attribute, extra.merge(options))
      builder.conflicting?
      builder.build

      # Additional settings for the builder
      instance_exec(builder, &block) if block.present?
    rescue Interrupt
      # Not able to build the attribute, maybe pending migrations
    end
  end
end

.search_vector_options(columns:, language: nil, stored: true, **options) ⇒ Object



29
30
31
32
33
34
35
36
37
38
# File 'lib/torque/postgresql/attributes/builder.rb', line 29

def self.search_vector_options(columns:, language: nil, stored: true, **options)
  weights = to_search_weights(columns)
  operation = to_search_vector_operation(language, weights).to_sql

  options[:index] = {
    using: PostgreSQL.config.full_text_search.default_index_type,
  } if options[:index] == true

  options.merge(type: :tsvector, as: operation, stored: stored)
end

.to_search_vector_operation(language, weights) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/torque/postgresql/attributes/builder.rb', line 50

def self.to_search_vector_operation(language, weights)
  language ||= PostgreSQL.config.full_text_search.default_language
  language = ::Arel.sql(language.is_a?(Symbol) ? language.to_s : "'#{language}'")
  simple = weights.size == 1

  empty_string = ::Arel.sql("''")
  operations = weights.map do |column, weight|
    column = ::Arel.sql(column.to_s)
    weight = ::Arel.sql("'#{weight}'")

    op = FN.to_tsvector(language, FN.coalesce(column, empty_string))
    op = FN.setweight(op, weight) unless simple
    op
  end

  FN.concat(*operations)
end

.to_search_weights(columns) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/torque/postgresql/attributes/builder.rb', line 40

def self.to_search_weights(columns)
  if !columns.is_a?(Hash)
    extras = columns.size > 3 ? columns.size - 3 : 0
    weights = %w[A B C] + (['D'] * extras)
    columns = Array.wrap(columns).zip(weights).to_h
  end

  columns.transform_keys(&:to_s)
end