sberry
sberry

Reputation: 132138

Pass arguments to ruby function in this context

disclaimer I am pretty new to Ruby / Rails

I am using RPH::Navigation for creating my navigation menus. What I am trying to do now is add some sub-nav items and I am doing so like this:

  suboptions.each do |group|
    def relpath
      link(group[:link], group[:args]).
    end 
    sub_menu.item group[:name], :path => :relpath
  end    

link is just a method that returns "#{link}?#{query_string}" where query_string is built from the args hash.

What I was originally trying to do was something like

    sub_menu.item group[:name], :path => link(group[:link], group[:args])

but that put the return value in, and later it is called, returning a method not found error.

My current approach has the problem that group is not in scope within relpath. I tried also using Proc.new and lambda, but since those are not called like normal functions it chokes on them as well.

What can I do to correct this? What is the proper way?

EDIT

If I do

suboptions.each do |group|
  def relpath(group)
    link(group[:link], group[:args]).
  end 
  sub_menu.item group[:name], :path => relpath(group)
end 

Then the error I get is:

undefined method `mylink?myarg=1' for #<#<Class:0x007fd8068acd58>:0x007fd8068b07f0>

EDIT 2

Here is more extensive example of the code.

menu.item MyTestsController, :text => 'Test', :if => Proc.new { |view| view.can? :read, MyTest } do |sub_menu|
  suboptions = [{:link => "tests", :name => "All Systems", :args => {:system_id => 0}},
                {:link => "tests", :name => "System A", :args => {:system_id => 1}}]
  suboptions.each do |group|
    def relpath(group)
      link(group[:link], group[:args]).
    end 
    sub_menu.item group[:name], :path => relpath(group)
  end 
end 

Upvotes: 1

Views: 326

Answers (1)

vaek
vaek

Reputation: 321

I have no experience with the navigation library in question, but looking at the documentation at https://github.com/rpheath/navigation it seems you are expected to give the name of a Rails named route helper as the path argument - not an actual URL route. The "undefined method" is simply generated because RPH::Navigation tries to call a helper method by the name that is defined in :path argument, and in this case Rails cannot find a named route helper method called "mylink?myarg=1". So basically, what you would need to do is to create a named route, and use that as the path.

Upvotes: 1

Related Questions