Forum: Ruby Help needed to DRY helpers and proper MVC with Ruby

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2cfdef9e499a6fad5d009b8d79c868f3?d=identicon&s=25 Becca Girl (newrubygirl)
on 2007-07-27 21:04
Hello.

I've got working code, but I don't think that it's done properly so any
help to make this more efficient and most of all, correct, would be so
very appreciated.

In my users_helper.rb file

 def generate_sub_nav
   if session[:user]
      sub_nav_menu = []
  user = User.find(session[:user])
        for role in user.roles
          for right in role.rights
            if right.on_menu
      sub_nav_menu << right.id
            end
        end # for right
      end # for role
    end # if
     sub_nav_menu.sort!
  end # def


In my application_helper.rb file for the layout and display

def show_sub_nav(rights)
  html_out = '<table><tr><td>'

  for right in rights
    right_array = Right.find(:all, :conditions => ["id = ?", right])
    for menu in right_array
      html_out << link_to_unless_current (menu.name,
:controller => menu.controller,                :action => menu.action)
    end
  end #for right in rights

  html_out << '</td></tr></table>'
  html_out
end



In my controllers (not including the user_controller)

helper :users


There's got to be a better, more Ruby like way to do this.

THANKS!
E1f43bafda26307a050d11902752b2a6?d=identicon&s=25 Ball, Donald A Jr (Library) (Guest)
on 2007-07-27 21:19
(Received via mailing list)
> I've got working code, but I don't think that it's done
> properly so any help to make this more efficient and most of
> all, correct, would be so very appreciated.

Your question is perhaps best asked on the rails list. There are a
couple of different things you could do to make your ActiveRecord usage
more efficient, but this isn't the forum for that.

http://lists.rubyonrails.org/mailman/listinfo/rails

As far as making this code more rubyish, most rubyists seem to prefer
iterators with blocks, e.g.:

user.roles.each do |role|
  role.rights.each do |right|
    ...
  end
end

to for loops.

- donald
This topic is locked and can not be replied to.