html_safe in ruby on rails not working - ruby-on-rails

I'm using ruby 2.0.0
This is my controller..
#mail_msg = #store_items.where(id: params[:button_id]).first.email_confirmation_text
p "-------------------------"
p #mail msg
p #mail_msg.html_safe
This is my console(terminal) output
"-------------------------"
"<p>You have purchased Spice It Up. Points have been redeemed from your main account.</p>"
"<p>You have purchased Spice It Up. Points have been redeemed from your main account.</p>"
And what im getting in my console is the same. I cant escape the html tags.
Update
I have this value in my view..
in my view page
<%= #mail_msg.html_safe %>
Still its not working..
Please help

Try these one may will help you
strip_tags("Strip <i>these</i> tags!")
# => Strip these tags!
strip_tags("<b>Bold</b> no more! <a href='more.html'>See more here</a>...")
# => Bold no more! See more here...
strip_tags("<div id='top-bar'>Welcome to my website!</div>")
# => Welcome to my website!enter code here

html_safe and raw work in views, use
<%= raw #mail_msg %>
or
<%= #mail_msg.html_safe %>

Related

Can't render line breaks in Rails with simple_format

I'm aware that in order to render \r\n I need to use simple_format, however it doesn't work on my posts that I migrated from WordPress. I tried many solutions including regex to replace \r\n with break tags, but it didn't help either. I still see on the screen all the line breaks printed out as text and not rendered.
Here is what I tried:
<%= simple_format(#post.body) %>
<%= simple_format(#post.body.gsub(/(?:\n\r?|\r\n?)/, '<br>')) %>
If I just do something like below it will work.
<%= simple_format "<h1>Briefed while smartwatch firm Pebble lays off 25% of its staff</h1> -\r\n\r\n \r\n <p>hello</p>" %>
I have no idea what am I doing wrong.
Try following, it should works for you, I have tested, its working
> "\n\r".gsub(/[\r\n]+/, '<br>') => "<br>"
> "\r\n".gsub(/[\r\n]+/, '<br>') => "<br>"
In your case
(#post.body.gsub(/[\r\n]+/, '<br>')
I finally solved it using an SQL query:
UPDATE posts SET body = REPLACE(body, '\r\n', '<br>');
Don't know why Rails gsub didn't work.
Edit:
Looks like my regex was wrong. This solves it too:
<%= simple_format(#post.body.gsub(/\\r\\n/, "\n")) %>

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.

Spaces inserted in browser in <pre> with Rails

A simple test case:
<% content = "<pre>a\nb</pre>" %>
<%= raw content %>
Browser Screenshot, with inserted spaces on second line:
Here's where it gets interesting. In rails:
raw(content).size # => 14 (correct)
But, in JS:
$("pre").html().length // => 13 (should be 3)
Any chance you are using HAML for your layout? If so, that would explain it as HAML will indent things for you. You can use HAML's ~ to get around this.
See: http://haml.info/docs/yardoc/file.REFERENCE.html#tilde

ruby on rails/javascript - errors with escaping html characters

In my RoR application, user selects an option from a popup and the selected value is passed to hidden fields found in my parent form.
The problem is when passing values containing html characters (e.g. <a href= ""> ) to the parent form.
In my popup, i have a link as follows which passes a value to the main form:
popup code:
<% #users.each do |user| %>
<%= link_to_function "PassValue", "sendValue('"+ user.location+ "')" %>
<% end %>
application.js:
function sendValue(location){
window.opener.document.getElementById('submission_user_attributes_location').value = location;
}
The location value retrieved form the database can contain html chars like '', and this is where my sendValue function is not working.
Please can someone help me on this.
Many many thanks in advance for your help :)
Please do not use obstrusive javascript. Try rewriting this code using non obstrusive javascript and it will prevent you from running into more problems in the future. See this railscast for more info: http://railscasts.com/episodes/205-unobtrusive-javascript
This being said, you could fix your problem by encoding your user.location with URI.encode, or escape quotes manualy or use escape_javascript.
My favorite solution is escape_javascript. From the documentation:
escape_javascript - Escape carrier
returns and single and double quotes
for JavaScript segments.
# File actionpack/lib/action_view/helpers/javascript_helper.rb, line 50
def escape_javascript(javascript)
if javascript
javascript.gsub(/(\\|<\/|\r\n|[\n\r"'])/) { JS_ESCAPE_MAP[$1] }
else
''
end
end

rails3 + liquid parse question

I have a question in using luquid. My question is like this,
I have a model called 'Page' (with is an ActiveRecord::Base
inherited) , and it has a column called 'content' which will store
the html page content.
I have a code to display it as follows
<%#template = Liquid::Template.parse(page_content) %>
<%= #template.render('page_content' => yield) %>
where 'page_content' has implemented in application helper as follows
def current_site_layout
Page.find(1). content
end
but my problem is if I have content as follows
<h1>This is a test</h1>
It will display in the page as
<h1>This is a test</h1> (with <h1></ h1> tags)
where as I want it to print like This is a test (formatting
applied as h1)
what am I missing here , and I think I will have to use liquid_methods
or something like that. But since I'm new to liquid I'm not sure which
method to use.. can someone help me
I'm on rails3 and using gem 'liquid 2.2.2', from 'github.com/GnomesLab/
liquid.git'
thanks in advance
cheers
sameera
In rails 3, strings are escaped by default. To display unescaped strings, you need to call raw method explicitly.
<%#template = Liquid::Template.parse(page_content) %>
<%= raw #template.render('page_content' => yield) %>

Resources