Class: Readymade::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/readymade/response.rb

Defined Under Namespace

Classes: NonKeywordArgumentsError

Constant Summary collapse

DEFAULT_STATUSES =
%i[success fail].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(status, *args) ⇒ Response

Returns a new instance of Response.



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/readymade/response.rb', line 17

def initialize(status, *args)
  @status = status.to_s

  raise NonKeywordArgumentsError if args.present? && !args[0].is_a?(Hash)

  @args = @data = args[0]
  @consider_success = @args.delete(:consider_success) if @args.present?

  define_singleton_method("#{status}?") do
    true
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



52
53
54
55
56
# File 'lib/readymade/response.rb', line 52

def method_missing(method_name, *args, &block)
  return false if method_name.to_s.end_with?('?')

  super
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



15
16
17
# File 'lib/readymade/response.rb', line 15

def args
  @args
end

#dataObject (readonly)

Returns the value of attribute data.



15
16
17
# File 'lib/readymade/response.rb', line 15

def data
  @data
end

#statusObject (readonly)

Returns the value of attribute status.



15
16
17
# File 'lib/readymade/response.rb', line 15

def status
  @status
end

Instance Method Details

#consider_success?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/readymade/response.rb', line 48

def consider_success?
  @consider_success
end

#errorsObject



30
31
32
33
34
# File 'lib/readymade/response.rb', line 30

def errors
  return {} unless args.is_a?(Hash)

  args[:errors].presence || {}
end

#humanize_errors(errors) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/readymade/response.rb', line 40

def humanize_errors(errors)
  if errors.is_a?(ActiveModel::Errors)
    errors.full_messages.join('. ')
  else
    errors.map { |k, values| "#{k.to_s.humanize}: #{values.join(', ')}" }.join('. ')
  end
end

#humanized_errorsObject



36
37
38
# File 'lib/readymade/response.rb', line 36

def humanized_errors
  humanize_errors(errors)
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


58
59
60
# File 'lib/readymade/response.rb', line 58

def respond_to_missing?(method_name, include_private = false)
  method_name.to_s.end_with?('?') || super
end