The correct way to get the segament key in url when used with hash_routes?

11 views
Skip to first unread message

Billy Zheng

unread,
Nov 19, 2021, 4:17:40 AM11/19/21
to Roda
Following is a example:

```rb
# app.rb

r.on Integer do |id|
  @insider_id = id
  r.hash_routes('insiders/show')
end
```

```rb

class App
  hash_routes('insiders/show') do
      is true do |r|
      result = RetrieveInsiderHistory.result(r.params.merge(insider_id: @insider_id))
      # ...
      end
  end
 end
```

Sure, as describe on README, we can access @insider_id which defined on `main` route in hash_routes, but, i am not sure if this the expected way to do this. anyway, when inspect the `r` variable, we can see App::RodaRequest object is there. 

[7] pry(#<App>)> r                                                                             
#<App::RodaRequest GET /insiders/1>


so, if there exists a way, to get the `1` Integer matcher from `r`?

Thank you.

Jeremy Evans

unread,
Nov 19, 2021, 10:43:17 AM11/19/21
to ruby...@googlegroups.com
On Fri, Nov 19, 2021 at 1:17 AM Billy Zheng <vil...@gmail.com> wrote:
Following is a example:

```rb
# app.rb

r.on Integer do |id|
  @insider_id = id
  r.hash_routes('insiders/show')
end
```

```rb

class App
  hash_routes('insiders/show') do
      is true do |r|
      result = RetrieveInsiderHistory.result(r.params.merge(insider_id: @insider_id))
      # ...
      end
  end
 end
```

Sure, as describe on README, we can access @insider_id which defined on `main` route in hash_routes, but, i am not sure if this the expected way to do this.

Yes, accessing the instance variable is definitely the recommended way to do this.
 
anyway, when inspect the `r` variable, we can see App::RodaRequest object is there. 

[7] pry(#<App>)> r                                                                             
#<App::RodaRequest GET /insiders/1>


so, if there exists a way, to get the `1` Integer matcher from `r`?

You could do:

  r.path.split('/').last.to_i

But you are much better off accessing the instance variable you created earlier.

Thanks,
Jeremy
Reply all
Reply to author
Forward
0 new messages