Aniket Tiwari
Aniket Tiwari

Reputation: 3998

Match dynamic data with match method

I am trying to match the dynamic route with the help of the match method but it is not working.

["payment", "portal", "animation"].each do |arg|
    define_method("profile_#{arg}") do 
        self.path.match("/users/\d+/#{arg}")
    end
end

So, this code self.path.match("/users/\d+/#{arg}") doesn't work with interpolation.

Whereas If I do something like below then it works. So, is there any way to match the data dynamically

self.path.match('/users/\d+/payment')
self.path.match('/users/\d+/portal')
self.path.match('/users/\d+/animation')

Upvotes: 0

Views: 111

Answers (2)

Sundeep
Sundeep

Reputation: 23667

You can interpolate within a regexp literal itself.

?> s = "payment"
=> "payment"
>> %r(/users/\d+/#{s})
=> /\/users\/\d+\/payment/

Upvotes: 1

anskeit
anskeit

Reputation: 43

The \d+ expression doesn't work properly with doublequotes and the string interpolation. Here a sample path for "portal" and 2x ways to match it. (Tested with 2.5.5)

path = "somedir/users/#{rand(0..999)}/portal"

["payment", "portal", "animation"].each do |arg|
    define_method("profile_#{arg}") do
        path.match("/users/"+(/\d+/).to_s+"/#{arg}")
        # or 
        path.match('users/\d+/'+arg)
    end
end

puts profile_payment
puts profile_portal
puts profile_animation

Upvotes: 1

Related Questions