0

I have a Project that has three arrays:

  • admins
  • members
  • readers

I want to email the various users in each of those arrays. Am currently doing it like:

@project.admins.each do |u|
  ProjelementMailer.notify_update(u)
end

@project.members.each do |u|
  ProjelementMailer.notify_update(u)
end

@project.readers.each do |u|
  ProjelementMailer.notify_update(u)
end

Is there a more DRY Rails approach that lets me express this in a more concise way?

2 Answers 2

1

Just combine all the arrays:

(@project.admins + @project.members + @project.readers).each do |u|
  ProjelementMailer.notify_update(u)
end

You may also wish to call uniq on the combined array to remove duplicates. For a more literal dynamic approach:

[:admins, :members, :readers].each do |sym|
  @project.send(sym).each do |u|
    ProjelementMailer.notify_update(u)
  end
end
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Andrew. Also appreciate the code with more literal dynamic approach.
@DanielMay Dynamic languages allow for many, many ways to accomplish the same (or similar) task. There is rarely one best solution, but it is always nice to explore them to find which one makes the most sense for a given application.
Yeah, I didn't grow up so much with dynamic languages and am trying to get acclimatised as much as possible to patterns (and anti-patterns). Thanks for your help on this :)
1

you can join all arrays using | for all uniq users and call each on it, but make sure all methods admins, members, readers are not returning nil object

(@project.admins | @project.members | @project.readers).each do |u|
  ProjelementMailer.notify_update(u)
end

3 Comments

Nice. Didn't know about | with arrays. Though don't call it bitwise OR, because it's not—it's a method that performs a union.
I know what it is, but you're saying it's something very different by saying "| (bit or)" in your answer.
Thanks Naren, helpful! Discussion also helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.