Stuck in parsing URL and work with it in a view

160 Views Asked by At

Trying to parse a URL with this format http://landing.com?data=123 - I'm been able to get the Data through irb like:

require "addressable/uri"
uri = Addressable::URI.parse("http://landing.com?data=123")
uri.query_values['data']
=> '123'

But I'm stuck on how to interact with that 'data' within a Rails view. I have tried including it in Controller (pages_controller.rb in my sample) like:

class PagesController < InheritedResources::Base

  def test
    uri = Addressable::URI.parse("<%= request.original_url %>")
    u = uri.query_values['data']
  end

end

But no idea how can I extract that piece of data to be used within my Views. Any guidance on this?

If I open one of the views like where I call that 'test' method - I'm getting uninitialized constant PagesController::Addressable but made sure it's in my enviroment with gem which addressable/uri

2

There are 2 best solutions below

3
Sophie Déziel On BEST ANSWER

Controllers have a lot of the query information already parsed. You can access it with params. In that case, you can use

u = params[:data]
0
Paulo Abreu On

As Sophie Déziel said, if it's under an app request, you can access to your query values through params hash. params is present in your controllers and views.

If you are talking about hardcoded URLs or URLS that you get from 3rd party sources, you will nee to create an instance variable in your controller (@u = ...) to be available in your views.

Note that you're not supposed to call action methods in your views, they are 'invoked' by Rails framework.

# controller
def my_action
  # .....
  @u = uri.query_values['data']
end

# view
<%= @u %>