Sha256: e0e34b62e080bb4c06fd21315eb56e99efe55a8cfd31d462dcada9e0bf968a92

Contents?: true

Size: 1.06 KB

Versions: 3

Compression:

Stored size: 1.06 KB

Contents

class CounterCacheUpdate::TableUpdatorService < ServicePattern::Service
  attr_reader :model_class, :reflection

  def initialize(reflection:)
    @reflection = reflection
    @model_class = @reflection.class_name.constantize
  end

  def execute!
    model_class.connection.execute(sql)
    ServicePattern::Response.new(success: true)
  end

private

  def column_name
    @column_name ||= proc do
      if reflection.options[:counter_cache] == true
        "#{reflection.active_record.name.pluralize.underscore}_count"
      else
        reflection.options[:counter_cache]
      end
    end.call
  end

  def count_sql
    "SELECT COUNT(*) FROM #{reflection_table_name} WHERE #{reflection_table_name}.#{relation_foreign_key} = #{table_name}.#{primary_key}"
  end

  def primary_key
    model_class.primary_key
  end

  def relation_foreign_key
    reflection.foreign_key
  end

  def reflection_table_name
    reflection.active_record.table_name
  end

  def sql
    "UPDATE #{table_name} SET #{column_name} = (#{count_sql})"
  end

  def table_name
    model_class.table_name
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
counter_cache_update-0.0.3 app/services/counter_cache_update/table_updator_service.rb
counter_cache_update-0.0.2 app/services/counter_cache_update/table_updator_service.rb
counter_cache_update-0.0.1 app/services/counter_cache_update/table_updator_service.rb