Module: Defaults

Defined in:
lib/defaults.rb,
lib/defaults/version.rb

Defined Under Namespace

Modules: ClassMethods, InstanceMethods, Version

Class Method Summary collapse

Class Method Details

.default_value(model, record, attribute) ⇒ Object



14
15
16
17
18
# File 'lib/defaults.rb', line 14

def self.default_value(model, record, attribute)
  value = model.default_values[attribute]
  value = Defaults.execute_callable(value, record) if value.respond_to?(:call)
  value
end

.default_value_for_column(model, attribute) ⇒ Object



9
10
11
12
# File 'lib/defaults.rb', line 9

def self.default_value_for_column(model, attribute)
  column_info = model.columns_hash[attribute.to_s]
  ActiveRecord::Type.lookup(column_info.type).cast(column_info.default) if column_info
end

.execute_callable(value, record) ⇒ Object



4
5
6
7
# File 'lib/defaults.rb', line 4

def self.execute_callable(value, record)
  callable = value.is_a?(Proc) ? value : value.method(:call)
  callable.arity == 1 ? value.call(record) : value.call
end

.included(base) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/defaults.rb', line 33

def self.included(base)
  base.extend ClassMethods

  class << base
    attr_accessor :default_values
  end
end

.resolve_default_value(model, record, attribute) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/defaults.rb', line 20

def self.resolve_default_value(model, record, attribute)
  attribute = attribute.to_sym

  # Check if value has been defined by `defaults`.
  # If it is, try to resolve by checking if value is callable.
  # Otherwise returns the default value of that column.
  if model.default_values.key?(attribute)
    Defaults.default_value(model, record, attribute)
  else
    Defaults.default_value_for_column(model, attribute)
  end
end