0

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

Shiva
  • 11,485
  • 2
  • 67
  • 84
malditojavi
  • 1,074
  • 2
  • 14
  • 28

2 Answers2

2

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]
Sophie Déziel
  • 428
  • 2
  • 11
  • So how would you render 'data' in a view/show of one of my Models, if that data does not belong to a Model? – malditojavi Jul 06 '16 at 07:21
  • 1
    Use an instance variable. `@u` instead of `u`. Be careful when displaying content of the URL or user generated content. You could create a vulnerability in your app to XSS attacks. – Sophie Déziel Jul 06 '16 at 20:15
  • @SophieDéziel +1 for `XSS` vulnerability alert – Shiva Jul 07 '16 at 03:36
0

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 %>
Paulo Abreu
  • 1,716
  • 11
  • 16