I have the following method that works fine. However, I think it is ugly. I am coming from the PHP world and am just learning Ruby. Is there a better way to write this method?
def _get_tasks(project_id)
_tasks = $dbh.select_all("SELECT * FROM tasks WHERE project_id=? ORDER BY name ASC;",project_id)
tasks = []
_tasks.each do |t|
_t = t.to_h
_t[:log] = $dbh.select_all("SELECT * FROM log WHERE task_id=? ORDER BY start DESC;",t[:task_id])
tasks.push _t
end
return tasks
end
My initial thought (and hope) would be the follow, but it is wrong because apparently the elements of the tasks Array aren’t actually hashes but DBI:Row objects. Any pointers?
def _get_tasks(project_id)
tasks = $dbh.select_all("SELECT * FROM tasks WHERE project_id=? ORDER BY name ASC;",project_id)
tasks.each do |t|
t[:log] = $dbh.select_all("SELECT * FROM log WHERE task_id=? ORDER BY start DESC;",t[:task_id])
end
return tasks
end
So there’s a bunch of comments suggesting you avoid the global and use classes or an ORM. They’re right, but I’m not going to fix that for you. If you just want this one function to be “prettier” and more idiomatic ruby, drop all the ugly underscores and temp vars and use enumerations.