Module: EventStoreClient::Extensions::OptionsExtension

Included in:
Config, Connection::Url, GRPC::Cluster::Member, GRPC::Connection, SerializedEvent
Defined in:
lib/event_store_client/extensions/options_extension.rb

Overview

A very simple extension that implements a DLS for adding attr_accessors with default values, and assigning their values during object initialization. Example. Let’s say you frequently do something like this: “‘ruby 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
end

end

SomeClass.new(attr1: ‘hihi’, attr4: ‘byebye’) “‘

You can replace the code above using the OptionsExtension: “‘ruby class SomeClass

include EventStoreClient::Extensions::OptionsExtension

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

end

SomeClass.new(attr1: ‘hihi’, attr4: ‘byebye’) “‘

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



63
64
65
66
67
# File 'lib/event_store_client/extensions/options_extension.rb', line 63

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

Instance Method Details

#initialize(**options) ⇒ Object



69
70
71
72
73
74
75
# File 'lib/event_store_client/extensions/options_extension.rb', line 69

def initialize(**options)
  self.class.options.each do |option|
    # init default values of options
    value = options.key?(option) ? options[option] : public_send(option)
    public_send("#{option}=", value)
  end
end

#options_hashHash

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

Returns:

  • (Hash)


80
81
82
83
84
# File 'lib/event_store_client/extensions/options_extension.rb', line 80

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