Module: ServiceObjects::Helpers::Messages

Included in:
Base, Exceptions, Validations
Defined in:
lib/service_objects/helpers/messages.rb

Overview

Note:

A target class should *include* the module

Features for collecting service messages

Instance Method Summary collapse

Instance Method Details

#add_message(options) ⇒ Array<ServiceObjects::Message>

Translates the text and adds a new message to the list of #messages

Examples:

class MyClass
  include ServiceObjects::Helpers::Messages
end

object = MyClass.new
object.add_message type: "foo", text: "bar", priority: 2.5
object.messages
# => [<ServiceObjects::Message type="foo" text="bar" priority=2.5>]

Options Hash (options):

  • :text (#to_s)

    the text of a new message to be translated via #translate method

  • :type (#to_s)

    the type of a new message

  • :priority (#to_f)

    optional priority fo a new message


74
75
76
77
78
79
80
# File 'lib/service_objects/helpers/messages.rb', line 74

def add_message(options)
  params   = Utils::NormalHash.from(options)
  type     = params.delete :type
  priority = params.delete :priority
  text     = translate params.delete(:text), params
  messages << Message.new(text: text, type: type, priority: priority)
end

#messagesArray<ServiceObjects::Message>

A list of object messages


47
48
49
# File 'lib/service_objects/helpers/messages.rb', line 47

def messages
  @messages ||= []
end

#translate(text, options = {}) ⇒ String

Translates the text in the current scope with given options

The method uses I18n.t library method.

Examples:

Returns a translation for symbolic argument

class Test
  include ServiceObjects::Helpers::Messages
end

MyClass.new.translate :item
# => translation not found: en.activemodel.messages.models.test.item

Converts non-symbolic argument to a string.

class Test
  include ServiceObjects::Helpers::Messages
end

MyClass.new.translate 1
# => "1"

39
40
41
42
# File 'lib/service_objects/helpers/messages.rb', line 39

def translate(text, options = {})
  return text.to_s unless text.is_a? Symbol
  I18n.t text, Utils::NormalHash.from(options).merge(scope: __scope__)
end