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?
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!).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With