Class: ActiveRecord::Materialized::View

Inherits:
Base
  • Object
show all
Extended by:
T::Sig
Includes:
RefreshCallbacks, ViewConfigurationClassMethods, ViewQueryAccessClassMethods
Defined in:
lib/activerecord/materialized/view.rb

Overview

The base class for an application-level materialized view. Subclass it, point ActiveRecord::Materialized::ViewConfigurationClassMethods::ClassMethods#materialized_from at an ‘ActiveRecord::Relation`, declare the models it depends_on, and then read it like any ActiveRecord model. Reads are served from a cache table the gem maintains incrementally as the underlying data changes; a full materialization happens only via an explicit rebuild!, and until then reads transparently fall through to the source query.

Examples:

Define a view and use it

class RegionRevenue < ActiveRecord::Materialized::View
  extend ActiveRecord::Materialized::QueryExpressions
  self.table_name = "mv_region_revenue"

  materialized_from do
    sales = Sale.arel_table
    Sale.group(:region).select(sales[:region], sum_as(sales[:amount], as: :revenue))
  end

  depends_on Sale            # writes to Sale schedule maintenance
  refresh_on_change :async   # refresh in the background after commit
  max_staleness 6.hours      # optional time-based safety net
end

RegionRevenue.rebuild!(confirm: true)              # materialize once (e.g. at deploy)
RegionRevenue.where(region: "west").pick(:revenue) # served from the cache table

See Also:

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ViewQueryAccessClassMethods

included

Methods included from ViewConfigurationClassMethods

included

Methods included from RefreshCallbacks

included

Class Attribute Details

.max_staleness_settingObject (readonly)

Returns the value of attribute max_staleness_setting.



63
64
65
# File 'lib/activerecord/materialized/view.rb', line 63

def max_staleness_setting
  @max_staleness_setting
end

.source_definitionObject (readonly)

Returns the value of attribute source_definition.



60
61
62
# File 'lib/activerecord/materialized/view.rb', line 60

def source_definition
  @source_definition
end

Class Method Details

.dependency_tablesObject



66
67
68
69
# File 'lib/activerecord/materialized/view.rb', line 66

def dependency_tables
  tables = T.let(T.unsafe(self).instance_variable_get(:@dependency_tables), T.nilable(T::Array[String]))
  tables.nil? ? [] : tables
end

Instance Method Details

#stale?Boolean

Returns:

  • (Boolean)


73
74
75
76
# File 'lib/activerecord/materialized/view.rb', line 73

def stale?
  T.bind(self, View)
  self.class.stale?
end