Class: Iry::Constraint::Check

Inherits:
Object
  • Object
show all
Defined in:
lib/iry/constraint/check.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, name:, message: :invalid) ⇒ Check

Returns a new instance of Check.

Parameters:

  • key (Symbol)

    key to apply error message for check constraint to

  • message (Symbol, String) (defaults to: :invalid)

    the validation error message

  • name (String)

    constraint name



28
29
30
31
32
33
34
35
36
# File 'lib/iry/constraint/check.rb', line 28

def initialize(
  key,
  name:,
  message: :invalid
)
  @key = key
  @message = message
  @name = name
end

Instance Attribute Details

#keySymbol

Returns:

  • (Symbol)


19
20
21
# File 'lib/iry/constraint/check.rb', line 19

def key
  @key
end

#messageSymbol, String

Returns:

  • (Symbol, String)


21
22
23
# File 'lib/iry/constraint/check.rb', line 21

def message
  @message
end

#nameString

Returns:

  • (String)


23
24
25
# File 'lib/iry/constraint/check.rb', line 23

def name
  @name
end

Class Method Details

.infer_name(key, table_name) ⇒ String

Infers the check constraint name based on key and table name

Parameters:

  • key (Symbol)
  • table_name (String)

Returns:

  • (String)


8
9
10
11
12
13
14
15
16
# File 'lib/iry/constraint/check.rb', line 8

def self.infer_name(key, table_name)
  # PostgreSQL convention:
  # "#{table_name}_#{key}_check"
  # Rails convention
  id = "#{table_name}_#{key}_chk"
  hashed_id = OpenSSL::Digest::SHA256.hexdigest(id)[0..9]

  "chk_rails_#{hashed_id}"
end

Instance Method Details

#apply(model) ⇒ ActiveModel::Error

Parameters:

Returns:

  • (ActiveModel::Error)


40
41
42
# File 'lib/iry/constraint/check.rb', line 40

def apply(model)
  model.errors.add(key, message)
end