ruby-on-railsarchitecturesoftware-designsolid-principles

Should I return string or array of emails?


I am creating a Rails application using JSON API Resources. It has employers and customers. The employer model has a name, website, and support emails, as attributes. Emails are stored using JSON serializer.

serialize :support_emails, JSON

To save support emails I added the following method in the employer model

def support_emails=(data)
    self[:support_emails] = data&.split(',')&.map { |email| email.strip.downcase }&.uniq
end

Support emails will be entered as comma-delimited strings in the text box.

In employer resource, I am returning support_emails as a string

def support_emails
    model.support_emails&.join(', ')
end

Here I and my colleague have different thoughts. My colleague says that we should return support_emails as it is. i.e. in Array format. Because displaying and reading should be done at the UI level. So, the logic to convert from array to string should be at the UI level not at the resource level.

My thought process is like this: I am getting the support_emails from the textbox as a comma-delimited string. So, the server should return data as it is received.

So, in this case, what should be the correct way?


Solution

  • Both solutions are valid. I don't think there is a best practice for that so it would just depend on your use case.

    How should the emails be displayed on the frontend after querying your API?

    If they will be displayed "separately", then it would be reasonable to send back the data in an array format. If you need to display the emails in a textbox like when they were sent in the beginning, then it would make sense to send the emails as a string.

    By the way, is there a particular reason why you don't send the emails as an array (see image below) through the API instead of sending a raw string and doing the parsing in the backend?

    enter image description here