Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Rails Way? (readability vs drying)

I have a User model, which have voting methods. I want to write proxy methods for voting.

This is readable way:

def vote_up item
  return false unless can? :vote, item
  vote item, :up
end

def vote_down item
  return false unless can? :vote, item
  vote item, :down
end

And this is DRY way:

%w(up down).each do |vtype|
  define_method "vote_#{vtype}" do |item|
    return false unless can? :vote, item
    vote item, vtype.to_sym
  end
end

Which one is better and why?

like image 358
enRai Avatar asked Jun 14 '12 13:06

enRai


1 Answers

Purely because OP seemed to like my comment, I'll put it as an answer:

Personally, considering you only have 2 methods here, and it's unlikely you'd ever add more (vote_sideways? vote_diagonally?) I would just go with the readable way. If you could potentially have many, many more though, I would go with the DRY way (because it becomes easily extendible) with a readable comment to explain to other developers (or to yourself later!).

like image 110
MrDanA Avatar answered Oct 13 '22 14:10

MrDanA