How could I DRY out the following piece of Rails code? The type parameter will correspond to Rails scopes, and I had assumed that all would work too … but it returns an array and my cunning plan fails.
The if looks wrong to me, but I can’t figure out how to have a all scope work correctly; any ideas?
Original code that improperly relied on all as a scope:
def readable(type=:all)
StudyAid.send(type.to_s).authored_by(self)
end
Working but ugly version:
def readable(type=:all)
if type == :all
StudyAid.authored_by(self)
else
StudyAid.send(type.to_s).authored_by(self)
end
end
I wouldn’t try and modify the behaviour of the
allmethod because that could unexpectedly change the semantics of other parts of your code and would surprise other people who came to work with your code.However you could define a named scope on
StudyAidwith a different name e.g.and then your method could become:
Minor point: you can use symbols with
sendso yourto_scall isn’t needed.Finally, I don’t think your version is as ugly as you think yourself.