Class: BlueprinterSchema::ModelAttributes

Inherits:
Object
  • Object
show all
Defined in:
lib/blueprinter_schema/model_attributes.rb

Overview

Resolves an attribute’s type and nullability from a model.

ActiveRecord models (responding to columns_hash) infer both the type and nullability from the column. ActiveModel objects (responding to type_for_attribute) infer the type from the attribute; nullability is inferred from presence validations when available, otherwise assumed nullable.

Instance Method Summary collapse

Constructor Details

#initialize(model) ⇒ ModelAttributes

Returns a new instance of ModelAttributes.



11
12
13
# File 'lib/blueprinter_schema/model_attributes.rb', line 11

def initialize(model)
  @model = model
end

Instance Method Details

#nullable?(name) ⇒ Boolean

Returns:

  • (Boolean)


23
24
25
26
27
28
29
30
31
32
# File 'lib/blueprinter_schema/model_attributes.rb', line 23

def nullable?(name)
  if active_record?
    column = @model.columns_hash[name]
    column ? column.null : false
  elsif active_model?
    active_model_nullable?(name)
  else
    false
  end
end

#type(name) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/blueprinter_schema/model_attributes.rb', line 15

def type(name)
  if active_record?
    @model.columns_hash[name]&.type
  elsif active_model?
    @model.type_for_attribute(name)&.type
  end
end