Ask A Question

Notifications

You’re not receiving notifications from this thread.

How to work with nested methods correctly

Freibuis asked in Ruby

I am trying to figure out how to pass parent arguments to child arguments of a nested method block

so I would like to do something like

namespace "top" do
  namespace "middle" do
    namespace "bottom" do
    end
  end
end

what I would like to have is to create a @namespaces var that stores each concated with its parent

def namespace(path, &block)
  (@namespaces ||= []) << [parent,path].join('/')
  instance_exec(block) if block_given?
end

I would like the value of @namespaces to be

[
  "top",
  "top/middle",
  "top/middle/bottom"
]

so the issue ... I can not figure out how to get the parent path of the outer method (or pass it to the child block)

any ideas?

Reply

Certainly! You can modify your namespace method to take the parent path as an argument and concatenate it with the current path. Here's a solution:

def namespace(path, parent_path = "", &block)
full_path = [parent_path, path].reject(&:empty?).join('/')
(@namespaces ||= []) << full_path
instance_exec(full_path, &block) if block_given?
end

namespace "top" do |top_path|
namespace "middle", top_path do |middle_path|
namespace "bottom", middle_path
end
end

puts @namespaces
Output:
[
"top",
"top/middle",
"top/middle/bottom"
]

This code uses the instance_exec method to pass the concatenated path to the next level of the block, which helps you create the desired @namespaces array.

Reply

this would only work if the namespace nesting would be perfect

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.