Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

ruby on rails - How to replace a pattern in a string

I built a page that is rendered differently depending on params. The logic is something like this:

<% if params[:x] == "1" %>
  <!--render version A-->
<% elsif params[:x] == "2" %>
  <!--render version B-->
<% elsif params[:x] == "3" %>
  <!--render version C-->
<% end %>

I want each version to have two links which link to the other two versions, so the urls should have different params. I have a url string original_url, which is:

"localhost:3000/page?x=1"

and want to replace its parameter depending on params. The other two versions should be:

"localhost:3000/page?x=2"
"localhost:3000/page?x=3"

How can I eliminate the pattern ?x=[number] from original_url and replace it with something else?

For version 1, I could do

request.original_url.sub("?x=1", "?x=2")

and then

request.original_url.sub("?x=1", "?x=3")

but then that wouldn't work on the other two versions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would do this for the links

<%= ([1,2,3]- [params[:x]]).each do |link_number| %>
   <%= link_to "Version #{link_number}", "/page?x=#{link_number}" %>
<% end %>

This way everytime the page is loaded the link to the other 2 versions will exist.

You could handle the partials through the controller (which seems better) or use something like:

<%= render "version_#{['A','B','C'][params[:x] - 1]}" %>

Without a better understanding of the problem I cannot assist beyond this point.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...