Sha256: 344573bc01e55ec642931b1b50222b85efa5e285c957883415cb4de8e3719701

Contents?: true

Size: 1.67 KB

Versions: 10

Compression:

Stored size: 1.67 KB

Contents

class ThinkingSphinx::ActiveRecord::Attribute::Type
  UPDATEABLE_TYPES = [:integer, :timestamp, :boolean, :float]

  def initialize(attribute, model)
    @attribute, @model = attribute, model
  end

  def multi?
    @multi ||= attribute.options[:multi] || multi_from_associations
  end

  def timestamp?
    type == :timestamp
  end

  def type
    @type ||= attribute.options[:type] || type_from_database
  end

  def type=(value)
    @type = attribute.options[:type] = value
  end

  def updateable?
    UPDATEABLE_TYPES.include?(type) && single_column_reference?
  end

  private

  attr_reader :attribute, :model

  def associations
    @associations ||= begin
      klass = model
      attribute.columns.first.__stack.collect { |name|
        association = klass.reflect_on_association(name)
        klass       = association.klass
        association
      }
    end
  end

  def klass
    @klass ||= associations.any? ? associations.last.klass : model
  end

  def multi_from_associations
    associations.any? { |association|
      [:has_many, :has_and_belongs_to_many].include?(association.macro)
    }
  end

  def single_column_reference?
    attribute.columns.length == 1               &&
    attribute.columns.first.__stack.length == 0 &&
    !attribute.columns.first.string?
  end

  def type_from_database
    db_column = klass.columns.detect { |db_column|
      db_column.name == attribute.columns.first.__name.to_s
    }

    if db_column.type == :integer && db_column.sql_type[/bigint/i]
      return :bigint
    end

    case db_column.type
    when :datetime, :date
      :timestamp
    when :text
      :string
    when :decimal
      :float
    else
      db_column.type
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
thinking-sphinx-3.1.0 lib/thinking_sphinx/active_record/attribute/type.rb
thinking-sphinx-3.0.6 lib/thinking_sphinx/active_record/attribute/type.rb
thinking-sphinx-3.0.5 lib/thinking_sphinx/active_record/attribute/type.rb
thinking-sphinx-3.0.4 lib/thinking_sphinx/active_record/attribute/type.rb
thinking-sphinx-3.0.3 lib/thinking_sphinx/active_record/attribute/type.rb
thinking-sphinx-3.0.2 lib/thinking_sphinx/active_record/attribute/type.rb
thinking-sphinx-3.0.1 lib/thinking_sphinx/active_record/attribute/type.rb
thinking-sphinx-3.0.0 lib/thinking_sphinx/active_record/attribute/type.rb
thinking-sphinx-3.0.0.rc lib/thinking_sphinx/active_record/attribute/type.rb
thinking-sphinx-3.0.0.pre lib/thinking_sphinx/active_record/attribute/type.rb