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
- #initialize(**options) ⇒ Object
-
#options_hash ⇒ Hash
Construct a hash from options, where key is the option’s name and the value is option’s value.
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. = 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(**) self.class..each do |option| # init default values of options value = .key?(option) ? [option] : public_send(option) public_send("#{option}=", value) end end |
#options_hash ⇒ Hash
Construct a hash from options, where key is the option’s name and the value is option’s value
80 81 82 83 84 |
# File 'lib/event_store_client/extensions/options_extension.rb', line 80 def self.class..each_with_object({}) do |option, res| res[option] = public_send(option) end end |