Module: Caprese::Typing

Extended by:
ActiveSupport::Concern
Included in:
Controller
Defined in:
lib/caprese/controller/concerns/typing.rb

Instance Method Summary collapse

Instance Method Details

#controller_record_classClass

Gets the record class for the current controller

Returns:

  • (Class)

    the record class for the current controller



33
34
35
# File 'lib/caprese/controller/concerns/typing.rb', line 33

def controller_record_class
  record_class(unnamespace(params[:controller]))
end

#fail_on_type_mismatch(type) ⇒ Object

Checks if a given type mismatches the controller type

Parameters:

  • type (String)

    the pluralized type to check (‘products’,‘orders’,etc.)



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/caprese/controller/concerns/typing.rb', line 40

def fail_on_type_mismatch(type)
  failed = false

  begin
    failed = record_class(type) != controller_record_class
  rescue NameError
    failed = true
  end

  if failed
    invalid_typed_record = controller_record_class.new
    invalid_typed_record.errors.add(:type)

    fail RecordInvalidError.new(invalid_typed_record, engaged_field_aliases)
  end
end

#record_class(type) ⇒ Class

Note:

“record type” can be plural, singular, or classified i.e. ‘orders’, ‘order’, or ‘Order’

Gets the class for a record type

Examples:

record_class(:orders) # => Order

Parameters:

  • type (Symbol)

    the record type to get the class for

Returns:

  • (Class)

    the class for a given record type



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/caprese/controller/concerns/typing.rb', line 18

def record_class(type)
  begin
    type.to_s.classify.constantize
  rescue NameError => e
    if resource_type_aliases[type.to_sym]
      record_class(resource_type_aliases[type.to_sym].to_sym)
    else
      raise e
    end
  end
end