Module: PgEventstore::Extensions::OptionsExtension

Included in:
Config, PgEventstore::Event, Partition, Subscription, SubscriptionsSet
Defined in:
lib/pg_eventstore/extensions/options_extension.rb

Overview

A very simple extension that implements a DSL for adding attr_accessors with default values, and assigning their values during object initialization. Example. Let’s say you frequently do something like this:

class SomeClass
  attr_accessor :attr1, :attr2, :attr3, :attr4

  def initialize(opts = {})
    @attr1 = opts[:attr1] || 'Attr 1 value'
    @attr2 = opts[:attr2] || 'Attr 2 value'
    @attr3 = opts[:attr3] || do_some_calc
    @attr4 = opts[:attr4]
  end

  def do_some_calc
    "Some calculations"
  end
end

SomeClass.new(attr1: 'hihi', attr4: 'byebye')

You can replace the code above using the OptionsExtension:

class SomeClass
  include PgEventstore::Extensions::OptionsExtension

  option(:attr1) { 'Attr 1 value' }
  option(:attr2) { 'Attr 2 value' }
  option(:attr3) { do_some_calc }
  option(:attr4)

  def do_some_calc
    "Some calculations"
  end
end

SomeClass.new(attr1: 'hihi', attr4: 'byebye')

Defined Under Namespace

Classes: Option, Options, ReadonlyAttributeError

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



132
133
134
135
136
# File 'lib/pg_eventstore/extensions/options_extension.rb', line 132

def self.included(klass)
  klass.singleton_class.attr_accessor(:options)
  klass.options = Options.new.freeze
  klass.extend(ClassMethods)
end

Instance Method Details

#initialize(**options) ⇒ Object



138
139
140
141
# File 'lib/pg_eventstore/extensions/options_extension.rb', line 138

def initialize(**options)
  @readonly = Set.new
  init_default_values(options)
end

#options_hashHash Also known as: attributes_hash

Construct a hash from options, where key is the option’s name and the value is option’s value

Returns:

  • (Hash)


146
147
148
149
150
# File 'lib/pg_eventstore/extensions/options_extension.rb', line 146

def options_hash
  self.class.options.each_with_object({}) do |option, res|
    res[option.name] = public_send(option.name)
  end
end

#readonly!(opt_name) ⇒ Boolean

Parameters:

  • opt_name (Symbol)

Returns:

  • (Boolean)


155
156
157
158
159
160
# File 'lib/pg_eventstore/extensions/options_extension.rb', line 155

def readonly!(opt_name)
  return false unless self.class.options.include?(Option.new(opt_name))

  @readonly.add(opt_name)
  true
end

#readonly?(opt_name) ⇒ Boolean

Parameters:

  • opt_name (Symbol)

Returns:

  • (Boolean)


164
165
166
# File 'lib/pg_eventstore/extensions/options_extension.rb', line 164

def readonly?(opt_name)
  @readonly.include?(opt_name)
end