Module: Outbox::MessageFields
- Included in:
- Outbox::Messages::Base
- Defined in:
- lib/outbox/message_fields.rb
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
Instance Method Summary collapse
-
#[](name) ⇒ Object
Read an arbitrary field.
-
#[]=(name, value) ⇒ Object
Add an arbitray field.
-
#fields(new_fields = nil) ⇒ Object
Returns a hash of the defined fields.
-
#fields=(new_fields) ⇒ Object
Assigns the values of the given hash.
-
#validate_fields ⇒ Object
Checks the current values of the fields and raises errors for any validation issues.
Class Method Details
.included(base) ⇒ Object
3 4 5 6 |
# File 'lib/outbox/message_fields.rb', line 3 def self.included(base) base.extend Outbox::DefineInheritableMethod base.extend ClassMethods end |
Instance Method Details
#[](name) ⇒ Object
Read an arbitrary field.
Example:
['foo'] = '1234'
['foo'] #=> '1234'
148 149 150 |
# File 'lib/outbox/message_fields.rb', line 148 def [](name) @fields[name.to_sym] end |
#[]=(name, value) ⇒ Object
Add an arbitray field.
Example:
['foo'] = '1234'
['foo'] #=> '1234'
158 159 160 |
# File 'lib/outbox/message_fields.rb', line 158 def []=(name, value) @fields[name.to_sym] = value end |
#fields(new_fields = nil) ⇒ Object
Returns a hash of the defined fields.
class SomeMessageType < Outbox::Messages::Base
fields :to, :from
end
= SomeMessageType.new to: 'Bob'
.from 'John'
.fields #=> { to: 'Bob', from: 'John' }
Also allows you to set fields if you pass in a hash.
.fields to: 'Bob', from: 'Sally'
.fields #=> { to: 'Bob', from: 'Sally' }
175 176 177 178 179 180 181 182 183 184 185 |
# File 'lib/outbox/message_fields.rb', line 175 def fields(new_fields = nil) if new_fields.nil? fields = {} self.class.fields.each do |field| fields[field] = public_send(field) end fields else self.fields = new_fields end end |
#fields=(new_fields) ⇒ Object
Assigns the values of the given hash.
.to = 'Bob'
.fields = { from: 'Sally' }
.fields #=> { to: 'Bob', from: 'Sally' }
192 193 194 195 196 |
# File 'lib/outbox/message_fields.rb', line 192 def fields=(new_fields) new_fields.each do |field, value| public_send(field, value) if respond_to?(field) end end |
#validate_fields ⇒ Object
Checks the current values of the fields and raises errors for any validation issues.
200 201 202 203 204 205 206 207 |
# File 'lib/outbox/message_fields.rb', line 200 def validate_fields self.class.required_fields.each do |field| value = public_send(field) if value.nil? || value.respond_to?(:empty?) && value.empty? raise Outbox::MissingRequiredFieldError, "Missing required field: #{field}" end end end |