class Ably::Models::Stats::StatsStruct

StatsStruct is a basic Struct like class that allows methods to be defined on the class that will be retuned co-erced objects from the underlying hash used to initialize the object.

This class provides a concise way to create classes that have fixed attributes and types

@example

class MessageCount < StatsStruct
  coerce_attributes :count, :data, into: Integer
end

@api private

Attributes

hash[R]

Public Class Methods

coerce_attributes(*attributes) click to toggle source
# File lib/submodules/ably-ruby/lib/ably/models/stats_types.rb, line 18
def coerce_attributes(*attributes)
  options = attributes.pop
  raise ArgumentError, 'Expected attribute into: within options hash' unless options.kind_of?(Hash) && options[:into]

  @type_klass = options[:into]
  setup_attribute_methods attributes
end
new(hash) click to toggle source
# File lib/submodules/ably-ruby/lib/ably/models/stats_types.rb, line 46
def initialize(hash)
  @hash = hash || {}
end
type_klass() click to toggle source
# File lib/submodules/ably-ruby/lib/ably/models/stats_types.rb, line 26
def type_klass
  @type_klass
end

Private Class Methods

setup_attribute_methods(attributes) click to toggle source
# File lib/submodules/ably-ruby/lib/ably/models/stats_types.rb, line 31
def setup_attribute_methods(attributes)
  attributes.each do |attr|
    define_method(attr) do
      # Lazy load the co-erced value only when accessed
      unless instance_variable_defined?("@#{attr}")
        instance_variable_set "@#{attr}", self.class.type_klass.new(hash[attr.to_sym])
      end
      instance_variable_get("@#{attr}")
    end
  end
end