class SorbetRails::ModelPlugins::ActiveRecordSerializedAttribute

Public Instance Methods

any_serialized_columns?(columns_hash) click to toggle source
# File lib/sorbet-rails/model_plugins/active_record_serialized_attribute.rb, line 44
def any_serialized_columns?(columns_hash)
  columns_hash.keys.any? do |column_name|
    !serialization_coder_for_column(column_name).nil?
  end
end
attr_types_for_coder(serialization_coder) click to toggle source
# File lib/sorbet-rails/model_plugins/active_record_serialized_attribute.rb, line 51
def attr_types_for_coder(serialization_coder)
  case serialization_coder.to_s
  when 'Hash'
    # Hash uses YAML.load/YAML.dump, and permits pretty much any kind of Hash key
    'T::Hash[T.untyped, T.untyped]'
  when 'Array'
    # YAML.load/YAML.dump
    'T::Array[T.untyped]'
  when 'JSON'
    # ActiveSupport::JSON.encode/ActiveSupport::JSON.decode
    # note that Hash keys are Strings since this is JSON
    'T.any(T::Array[T.untyped], T::Boolean, Float, T::Hash[String, T.untyped], Integer, String)'
  else
    # unknown uses YAML.load/YAML.dump
    'T.any(T::Array[T.untyped], T::Boolean, Float, T::Hash[T.untyped, T.untyped], Integer, String)'
  end
end
generate(root) click to toggle source
# File lib/sorbet-rails/model_plugins/active_record_serialized_attribute.rb, line 6
def generate(root)
  columns_hash = @model_class.table_exists? ? @model_class.columns_hash : {}
  return unless any_serialized_columns?(columns_hash)

  serialize_module_name = self.model_module_name('GeneratedSerializedAttributeMethods')
  serialize_module_rbi = root.create_module(serialize_module_name)

  model_class_rbi = root.create_class(self.model_class_name)
  model_class_rbi.create_include(serialize_module_name)

  columns_hash.sort.each do |column_name, column_def|
    serialization_coder = serialization_coder_for_column(column_name)
    next unless serialization_coder

    nilable = nilable_column?(column_def)
    attr_type = attr_types_for_coder(serialization_coder)

    serialize_module_rbi.create_method(
      column_name.to_s,
      return_type: ColumnType.new(base_type: attr_type, nilable: nilable).to_s,
    )

    serialize_module_rbi.create_method(
      "#{column_name}=",
      parameters: [
        Parameter.new('value', type: ColumnType.new(base_type: attr_type, nilable: nilable).to_s)
      ],
      return_type: nil,
    )

    serialize_module_rbi.create_method(
      "#{column_name}?",
      return_type: 'T::Boolean',
    )
  end
end