Custom links in Rails - ruby-on-rails

Rails has a few built in helper methods for dealing with links (url_for, link_to, auto_link), but none do exactly what I need:
I want the user to be able to specify a URL, and for me to be able to alter the text it appears as. auto_link almost does what I want, except you can't change the link text, and it doesn't recognize links that are typed in like: stackoverflow.com. You have to enter www.stackoverflow.com
I want the user to be able to enter something like "stackoverflow.com", and for me to be able to generate html like this:
Username
Is there a plugin out there that adds additional link helper methods?

You can pass a block to auto_link, and the result of that will be the link text. For example:
<% str = "something like http://stackoverflow.com would be the input" %>
<%= auto_link(str) do |url|
"Username"
end
%>
generates this HTML:
something like Username would be the input
And if you wanted the link text to be different depending on what the URL was, you could do something like:
<% str = "something like http://stackoverflow.com, and another http://stackexchange.com url" %>
<%= auto_link(str) do |url|
if url.match(/overflow/)
"Username"
else
"Something"
end
end %>
which generates:
something like Username, and another Something url
This plus the tips in the comments about adjusting the URL regex seem like they would do what you want.

Related

How to interpolate ruby inside of an interpolated bit of ruby in ERB

I'm trying to create a situation where one user makes message templates and another one can plug in values. I'm using the best_in_place gem, which will allow a user to edit the message on the show page.
The problem is this. When I call the message, with the required erb to make the gem work, it treats all of this as a regular string, not as ruby.
This is unclear, I'm sorry.
Here's the code.
#announcement.content = "The <%= best_in_place #announcement, :train %> is arriving in five minutes."
/show.html.erb
<%= #announcement.content %>
I want it to put "The click to set train is arriving in five minutes." and if the user clicks where it says "click to set train," a text field will open for them to edit (this is something the best-in-place gem does).
Instead, it puts "The <%= best_in_place #announcement, :train %> is arriving in five minutes."
I understand why it is doing this, but I don't know how to make it instead interpret the ruby I'm trying to pass in.
Ideas?
Use regular old string interpolation:
#announcement.content = "The #{best_in_place #announcement, :train} is arriving in five minutes."
You can use ERB to render any ERB template string. In this case something like:
<%= ERB.new(#announcement.content).result %>
Although you likely won't have access to all your Rails helpers, etc.
The Rails way to do this:
#announcement.content_type = :arriving
Later:
<%= render(partial: #announcement.content_type)
In _arriving.erb:
The <%= best_in_place #announcement, :train %> is arriving in five minutes.
TL;DR: ERB is not Ruby, and Rails uses both at different times.
You want simple Ruby string interpolation here:
#announcement.content = "The #{best_in_place #announcement, :train} is arriving in five minutes."
This is unclear, I'm sorry.
Not to worry, the Rails framework throws so many different new concepts at you it can be frustrating for newcomers.
Start from this: the Ruby framework builds the answer to the user's browser from a collection of resources Each file is evaluated by an interpreter for its own language. The trick is: look at the extension.
Files ending in .coffee will be compiled into javascript, files ending in .scss will become CSS, and in the same way files ending in .erb will yield HTML.
ERB is a language composed of mostly HTML already, plus a tag that allows you to interpolate Ruby. ERB stands for Embedded Ruby.
What about files ending in .rb, like the file in which you (surely) are evaluating #announcement.content = "The <%= best_in_place[...]" (a controller, I guess)?
Well, that's just pure Ruby :) that's why the ERB interpolation syntax <%= ... > is not recognized.
What you want to do in the controller, is (as you're trying to do) preparing the data for the view. The ruby in the <%= ... > tag in ERB will have access to the controller's instance variables, i.e. the variables with an # in front defined in the controller. But to define those, inside the controller, you should rely on Ruby alone.
Take-home message:
Be aware of which language you are writing in at each moment. For example:
# show.html.erb
<p>Here is ERB, which will be interpreted straight into HTML</p>
<% "Inside the '<% ...' tag is Ruby, but results won't show up in the HTML because there's no '<%='."%>
<% which_language = "Ruby" # Even variable assignments, and comments, do work %>
<%= "Inside the '<%=' tag, you're writing and interpolating #{which_language} :)" %>
I think the fact that I wasn't clear made it hard to answer this question.
What I'm doing is transforming user-inputted text (using a method in the model, called by the controller) to replace certain keywords with erb tags that call the best_in_place plugin. In my view, when presenting this content to another user, I wanted to call this content, which is saved as an attribute in the database, in such a way that it would render correctly for the other user to have the best_in_place functionality active.
Here's what I ended up doing. It is working, but if you have better ideas, please let me know.
In the announcements#create view, the user creates an announcement with certain pre-defined blocks of bracketed text as well as free-input text. For example, they might write "[train] is leaving from [platform] in [time] minutes."
When they hit save, the controller's create action calls the construct_message method from the model. It looks like this:
def construct_message(msg)
msg.gsub! '[train]', '<%= best_in_place #announcement, :train_id, :as => :select, collection: Train::list_trains, place_holder: "Click here to set train." %>' #note: list_trains and list_platforms are methods on the model, not really important...
msg.gsub! '[platform]', '<%= best_in_place #announcement, :platform_id, :as => select, collection: Platform::list_platforms, placeholder: "Click here to set platform." %>'
msg.gsub! '[time]', '<%= best_in_place #announcement, :number_of_minutes, placeholder: "Click here to set." %>'
end
Then, when I want to show that attribute in my view, I'm using render :inline, like this.
on announcements/:id
<p id="notice"><%= notice %></p>
<p>
<strong>Content:</strong>
<% announcement = #announcement %>
<%= render :inline => announcement.content, locals: { :announcement => announcement } %>
</p>
This allows the erb call that I wrote into the attribute to be functional.
Also note that I'm choosing to use a local rather than instance variable here; this is because in announcements#index, I also render this text and the table there uses local variables.

Add arbitrary string to URLs in Rails/Middleman app

I'm using middleman to generate a static webpage. I need to add a consistent but understandable string to all urls so I can understand how users navigate on the page.
Now i do it like this
<% link_to '/'+?button=navigation , class: 'logotype', itemprop: 'url' do %>
...
<% end %>
I would prefer not having to manually add all the parameters but rather just use something that's already there, like a scope or something. I was thinking about using the name of the template file for example. The url is not unique enough.
Any suggestions?
The standard way of doing this would be to write a helper method that encapsulates your functionality:
<%= link_to_as_nav('/', class: 'logotype', ...) do %>
...
<% end %>
Then write a helper method:
def link_to_as_nav(url, options)
link_to(url + '?button=navigation', options)
end
This is the naïve approach and won't account for a url argument that already has parameters added, but that's something you can work to fix.

Rails, link_to helper with an URL as a param

I want to generate the next html link:
http://url.com
To reproduce it using the link_to helper I have to write:
<%= link_to "http://url.com", "http://url.com" %>
What doesn't look DRY at all, I was expecting this to work:
<%= link_to "http://url.com" %>
But the above code generate a link targeting the actual request.url, not the one I'm sending in the param.
Am I missing something?
You're not missing anything --- the normal case is for the URL and the text that shows to the user to be different.
If you'd like, you could create a helper like
def link_to_href(link, args={})
link_to link, link, args
end
then, when you use it,
<%= link_to_href "http://url.com" %>
Will output
http://url.com
If you take a look at the source code of link_to you will see that at line 248 the a tag label is build with name || url.
That's why you have this behaviour and there is noway to do it like you're expecting.

How to display a rails link_to in a raw (or simple_format) text

I have an image model with an attribute :description which is a text, formatted as html text (e.g. with a few in the text), which I display in a view as follows:
simple_format(#image.description)
raw(#image.description) will do mainly the same I think. How can I add a link_to helper with a link into that text? I'm searching for something like the following text (which will be #image.description):
Text text text text.
Text text #{link_to "Text", #image.link)
#image.link will be the link. How can I do this?
Use ERB:
<%= raw ERB.new(#image.description).result(binding) %>
Wrap it in a helper method:
module ApplicationHelper
def simple_format(content)
ERB.new(content).result(binding).html_safe
end
end
And use it like:
<%= simple_format(#image.description) %>
Some example content you could use for your image description could be:
Check out <%= link_to "the first image", image_path(1) %>!
You can do this with this bit of code
link_to raw(#image.description), #image.link
If you need select only one random word:
words = #image.description.split
link_to raw(words.sample), #image.link
UPDATE:
For example when you create description you can add special symbols to word which you can use as link for example it can be brackets:
#image.description = This my description with link (Hello) you can follow it!
#image.description.gsub(/\(([^\)]+)\)/, link_to('\1', #image.link))
It will produce:
"This my description with link Hello you can follow it!"

Message Module + handling links for private messages + rails

i'm creating an application where i need to send a private message to a user and ask him/her for a confirmation on whether they would like to join or not. I have created a private message module and whenever i want to send a message, i do something like :
def sendMessage(attributes)
subject = 'whatever'
body = 'whatever'
current_user.sendMessage(current_user, subject, body)
end
Then, i get this message and print it out to the needed places, using <%=h %> for escaping stuff. My problem now is, what happens if i want to include 's or even more importantly <%= link_to %> inside that ?
How can i insert such things to be printed out and also be careful about escaping the user provided attributes ? I was thinking of creating sort of like a partial to do this for me, but i would certainly like to hear what you think about it.
Thank you :)
First off, you probably should name your method send_message since that tends to be the convention in Ruby and Rails.
For the question, why not do this:
<p><%=h user_submitted_info %> and check out this <%= link_to "Awesome Link", "/" %></p>
This will escape the user submitted content but leave the link_to alone. Why does the user submitted content and the link need to be in the same ERB tags?

Resources