How do I use HAML in a dynamic link? - ruby-on-rails

I am trying to create a link using HAML which looks like the this
=link_to("Last updated on<%=#last_data.date_from.month %>",'/member/abc/def?month={Time.now.month}&range=xyz&year={Time.now.year}')
It is not taking the Ruby code and it is displaying that as a string
Last updated on<%=#last_data.date_from.month %>
and in the URL as well it is not taking the function Time.now.month or Time.now.year .
How do I pass Ruby code in URL and in the string ?

You should probably use something like this:
= link_to("Last updated on #{#last_data.date_from.month}", "/member/abc/def?month=#{Time.now.month}&range=xyz&year=#{Time.now.year}")
Note that in the second string, it's necessary to change the ' to ". Also if the link text is getting long, you can use something like this:
= link_to("/member/abc/def?month=#{Time.now.month}&range=xyz&year=#{Time.now.year}") do
Last updated on #{#last_data.date_from.month}

Everything after the = in HAML is a Ruby expression. Ruby doesn't interpolate strings the way HAML does, it has own way of such interpolation.
In Ruby, when you want to have string value of some variable inside another string, you could do.
"Some string #{Time.now}"
So, it should be:
= link_to "Last updated on #{#last_data.date_from.month}", "/member/abc/def?month=#{Time.now.month}&range=xyz&year=#{Time.now.year}"

A simple example with easy syntax:
link_to "Profile #{rubycode}", "profile_path(#profile)/#{ruby_code}", class: "active"

Related

Passing raw HTML to haml file

Is it possible to pass pre formatted HTML to the haml file. For example I pass a variable such as:
my_text = "<b>this is bold</b>"
Then in my haml file:
%p
=#my_text
I was hoping it would display This is bold
But it just returns the original string and ignores the tags surrounding "this is bold"
The goal is to highlight certain key words("one" and "two" in this example), here's a better example:
#my_text = "This <b>one</b> plus <b>one</b> is a total of <b>two</b>"
Not sure what you want to achieve, but i'd recommend that you keep your markup in the haml and plug in your copy in the instance variable like this.
MyTextController.rb
#my_text = this is bold
my_text.html.haml
%b
= #my_text
Edit after further clarification.
You can use sanitize helper for this.
my_text.html.haml
%p
= sanitize(#my_text, tags: %w(b))
Ahh I figured it out, looks like you can do:
%p
= raw #my_text

Creating a link with link_to and gsub

I have a body of text being fed into a textarea and if any of the text matches URI.regexp, I need to make that link active with a target: '_blank' on the a tag in the textarea.
Here is my current code. I also tried this with .match which would correc
def comment_body(text)
text = auto_link(text)
text.gsub!(URI.regexp) do |match|
link_to(match, match, target: '_blank')
end
end
This outputs:
https://facebook.com">https://facebook.com in my view
and
https://facebook.com in the inspected HTML.
In the gsub docs it says that metacharacters will be interpreted literally, which is what I believe is messing me up here.
Any tips on how to properly construct this URL?
Thanks!
The auto_link gem does exactly what you need.
You can look at its code to see how its using gsub.
EDIT: this solution requires setting sanitize to false, which often is not a good idea!
I've found a solution without using auto_link (I'm using Rails 5 too). I know this is an oldish thread but I've spent some time trying to find a solution that would allow the insertion of target="_blank" and found this. Here I'm creating a helper to search text in a text box for links and then add essentially make them linkable in the view.
def formatted_comment(comment)
comment = comment.body
URI.extract(comment, ['http', 'https']).each do |uri|
comment = comment.gsub( uri, link_to(uri, uri, target: "_blank"))
end
simple_format(comment, {}, class: "comment-body", sanitize: false)
end
The key thing here was simple_format kept sanitizing, so it's important to add both {} and sanitize:false.
***Note that setting sanitize to false may bring up other issues like allowing javascript to run in a comment, but this solution will allow the insertion of target="_blank" into a link.
One solution using just a simple gsub with back references would be something like this: (You can certainly modify the regex to meet your needs.)
str = 'here is some text about https://facebook.com and you really http://www.google.com should check it out.'
linked_str = str.gsub( /((http|https):\/\/(www.|)(\w*).(com|net|org))/,
'\4' )
Example output:
print linked_str
#=> here is some text about facebook and you really google should check it out.

Have trouble implement the variable loop in haml file

I use ruby on rails to get some variables and suppose to send them in email format to some email address.
%div
- #msg.each do |line|
%p = "#{line}"
%br
The msg is the string array I passed in and would like to get each element in separate line. How can I achieve that. The above code won't work.
One of the key things of coding HAML is you really are only going to have one item per line, plus you automatically get a div tag as the default tag. So you might as well add a class to your div to differentiate it. Additionally, make sure your indentation is correct:
.messages
- #msg.each do |line|
%p= line
You don't really need a br because the p will break for you, and following a tag with '=' will automatically give you the interpolation.

Getting strings from i18n YAML file?

I have some view code:
<span data-something="[<%= t('.asd') %>, <%= t('.dsf') %>]></span>
I use this code to get some dynamic strings translated into the view. My YAML is something like:
en:
feature:
asd: "Asdddd"
dsf: "adasdsadasda"
Is there a way I can use to dynamically get all the "features" from the YAML by locale and put it in the data-attribute?
This is pretty simple to do:
I18n.translate('feature').values.join(', ')
You'll end up with a string "Asdddd, adasdsadasda".
I think it's as easy as t('feature') to get the hash, you might want to just have the values so could you try t('feature').keys?

HAML - how to display the value of a variable?

I have a variabla var. If I try to output its value in HAML like =val then I just get the string value of the object which looks like this: #<ShortenedUrl:0x118c50fa.
But how do I get the value that is in there?
Using Haml
%h2
#{#project.name}
or
%h2
#{org.id}
I think you may want the .inspect method.
= val.inspect
That will show you something like:
#<ShortenedURL #url="the url", #count=0, #etc="etc">
Of course, if you want to dive in to specifics (for example, you only want to show someone the url attribute (or whatever attribute you may have), then use that method:
= val.url
Which will show:
the url

Resources