hey guys
when I store this string:
http://61.147.96.19/f4v/41/53283141.h264_2.f4v?10000&key=d7d7488b5dd4a35aac3e784cf4acb1a174ddc7&playtype=1&tk=2038443745&brt=3&id=tudou&itemid=30165756&fi=53283141&sz=19354294
in a variable #longurl
and use it in a erb file
<%= #longurl %>
It doesn't work, when I check the source file in the browser :
http://61.147.96.19/f4v/41/53283141.h264_2.f4v?10000&key=d7d7488b5dd4a35aac3e784cf4acb1a174ddc7&playtype=1&tk=2038443745&brt=3&id=tudou&itemid=30165756&fi=53283141&sz=19354294
and compare the differece, it add a amp; after each &, and I don't know how to avoid this.
BTW it seems #url is taken by the rails by default use, I can't save anything in the variable, Could anyone tell me why?
Thanks
Assuming you're using Rails 3, try <%= #longurl.html_safe %>.
You can use CGI::unescape to decode a URL-encoded string.
<%= CGI::unescape(#longurl) %>
For HTML entities, use CGI::unescapeHTML:
<%= CGI::unescapeHTML(#longurl) %>
You actually want &
Read why here: http://htmlhelp.com/tools/validator/problems.html
Is it 'breaking' the method in any other way, or just because it looks different?
If #url is used by Rails, use a different variable. It shouldn't be a deal breaker.
Before Rails 3, you used to have to code like this to make sure everything is HTML encoded:
<%= h #longurl %>
The h method would HTML encode your string. Now, everything is HTML encoded by default. If you don't want Rails to do this for you, we now have the raw method like this:
<%= raw #longurl %>
Read more about the raw method here:
http://api.rubyonrails.org/classes/ActionView/Helpers/RawOutputHelper.html#method-i-raw
or read about this change in the Rails 3 release notes
http://edgeguides.rubyonrails.org/3_0_release_notes.html#other-changes
Related
I'm using an API that I call with something like this:
Controller:
#bounces = SendgridToolkit::Bounces.new(API_USERNAME, API_PASSWORD)
View:
And that returns data like this: (for JSON, though an XML call is also possible)
[{"status"=>"550", "created"=>2015-07-06 18:37:38 UTC, "reason"=>"550 Unrouteable address ", "email"=>"jake#fake.com"}]
It's useful to me, but unfortunately it's not the way I want to present it in my Rails application. What's the best way to transform this data, since I don't have access to the poorly formatted string itself, only the code that requests it from the application I'm interacting with?
I'm having some issues coming up with the right question to ask Google, and would appreciate any suggestions you have to offer from experience.
Thanks in advance for your help!
EDIT:
For example, this returns an error no matter where I put it (The view or the controller), saying that string is an undefined method:
string = '[{"status":"550","reason":"550 Unrouteable address ","email":"jake#fake.com"}]'
#showbounces = #bounces.retrieve.to_json JSON.parse(string)
#newsletters = Newsletter.all
returns:
no implicit conversion of Symbol into Integer:
#showbounces = #bounces.retrieve.to_json JSON.parse(string)
Ultimately I'd like to extract select information from the JSON/XML and use it for things like graphs in my view that I can format with CSS and HTML.
You don't need to parse the JSON output string from the web service. The SendgridToolkit gem takes care of that. It returns the data as Ruby objects (arrays and/or hashes), ready to be used in your code.
For example, in your controller:
def index
bounces = SendgridToolkit::Bounces.new(API_USERNAME, API_PASSWORD)
#all_bounces = bounces.retrieve
end
and then in your view:
<ul>
<% #all_bounces.each do |bounce| %>
<li>Bounced <%= bounce['email'] %> (<%= bounce['reason'] %>)</li>
<% end %>
</ul>
I ran into a small problem today when I was trying to use sanitize and truncate in conjunction with one another to create an excerpt for my blog. Each of the methods worked by itself, but used together it would only truncate. I tried both of these syntaxes (the former being recommended in a blog post titled "Six Ruby on Rails Tips & Tricks"):
<%= truncate(sanitize(post.content), length: 580) %>
<%= sanitize(truncate(post.content, length: 580, separator: '<p>')) %>
And then I tried to put truncate in the controller, and sanitized that object in the view, but still no.
Finally I got it to work like this:
<%= sanitize(post.content.truncate(580, separator: '</p>')) %>
What I'd like to know is why didn't it work when I wrapped a method in another method? What's the difference with the last way I tried it?
TIA
'bondibox'
This worked for me:
<%= sanitize(article.description[0..100]) %>
Truncate and Sanitize are not included in controllers, they are part of ActionView::Helpers::TextHelper and ActionView::Helpers::SanitizeHelper respectively. These modules are not included per default in a controller, so you cannot use it in there.
However, both are included in the views (templates) and you can therefore use them in there. You can include the modules stated above in a controller class to use them there, but i would not recommend it.
The reason the second statement works is because Rails extends some base objects from Ruby, like String with several methods. so you actually call sanitize on a truncated version of a string truncated by a method of String.
The combination of both is a bit tricky. I cannot really tell you why the combination of the module version of sanitize and truncate does not work without a little more info. What exactly did you try to accomplish here (examples?)
An old question, but landed on it while struggling with this myself. The problem is that sanitize will not strip all HTML tags, but just a few that are defined by default, such as script. So you have to specifiy that no tags are allowed:
truncate sanitize(post.content, tags: [], attributes: []), length: 580
Thanks Ruben,
<%= sanitize(article.description[0..100]) %>
is working perfectly in Rails 6.
Our experience is that all other combinations w/ truncate aren't working.
I am running into an issue when looking into fragment-level caching within my Rails 3.0.4 application with memcached. I am a bit confused with what is going on, but I think it's something to do with the way the output is being pulled from within the caching region. I am running memcached locally in -vv mode, and can see the key for the fragment getting saved/pulled correctly, the problem is the value of the item within memcached.
Here is what I'm doing:
< ... html before ... >
<%= cache("item_#{i.id}") do %>
<%= render :partial => 'shared/item', :locals => { :item => i, :functionality => [:set_as_default] } %>
<% end %>
< ... html after ... >
When I look at the value of the key within the cache, it has html from within the page that is in that fragment cache block, but ALSO OUTSIDE of that (from both the html before and html after areas). Here is the interesting part though, and is kind of the reason I think its related to capturing the output--it doesn't do the whole page, only some of the html before and some after.
According to the rails fragment cacheing guide, I think I'm doing things correctly (http://guides.rubyonrails.org/caching_with_rails.html#fragment-caching). Does anyone have thoughts as to what could be going on?
Your help is much appreciated!
-Eric
In this case, you are using ERB incorrectly. Basically take out the = sign. What your doing is your returning the value of the block too and hence why you are seeing double output.
<% cache("item_#{i.id}") do %>
Also, ActiveRecord objects respond to an internally baked in #cache_key method. Try to take advantage of that. The default #cache_key for an ActiveRecord object uses the class name, the object id and the updated_at timestamp too. The cache method should be able to take multiple args or an array and it will inturn call cache_key for every object that responds to it. Using this method, it means you will cache miss when the object is updated to, pretty cool stuff. So, IIRC
<% cache("item",i) do %>
Suppose I have the following string
#x = "<a href='#'>Turn me into a link</a>"
In my view, I want a link to be displayed. That is, I don't want everything in #x to be unescaped and displayed as a string. What's the difference between using
<%= raw #x %>
<%= h #x %>
<%= #x.html_safe %>
?
Considering Rails 3:
html_safe actually "sets the string" as HTML Safe (it's a little more complicated than that, but it's basically it). This way, you can return HTML Safe strings from helpers or models at will.
h can only be used from within a controller or view, since it's from a helper. It will force the output to be escaped. It's not really deprecated, but you most likely won't use it anymore: the only usage is to "revert" an html_safe declaration, pretty unusual.
Prepending your expression with raw is actually equivalent to calling to_s chained with html_safe on it, but is declared on a helper, just like h, so it can only be used on controllers and views.
"SafeBuffers and Rails 3.0" is a nice explanation on how the SafeBuffers (the class that does the html_safe magic) work.
I think it bears repeating: html_safe does not HTML-escape your string. In fact, it will prevent your string from being escaped.
<%= "<script>alert('Hello!')</script>" %>
will put:
<script>alert('Hello!')</script>
into your HTML source (yay, so safe!), while:
<%= "<script>alert('Hello!')</script>".html_safe %>
will pop up the alert dialog (are you sure that's what you want?). So you probably don't want to call html_safe on any user-entered strings.
The difference is between Rails’ html_safe() and raw(). There is an excellent post by Yehuda Katz on this, and it really boils down to this:
def raw(stringish)
stringish.to_s.html_safe
end
Yes, raw() is a wrapper around html_safe() that forces the input to String and then calls html_safe() on it. It’s also the case that raw() is a helper in a module whereas html_safe() is a method on the String class which makes a new ActiveSupport::SafeBuffer instance — that has a #dirty flag in it.
Refer to "Rails’ html_safe vs. raw".
html_safe :
Marks a string as trusted safe. It will be inserted into HTML with no additional escaping performed.
"<a>Hello</a>".html_safe
#=> "<a>Hello</a>"
nil.html_safe
#=> NoMethodError: undefined method `html_safe' for nil:NilClass
raw :
raw is just a wrapper around html_safe. Use raw if there are chances that the string will be nil.
raw("<a>Hello</a>")
#=> "<a>Hello</a>"
raw(nil)
#=> ""
h alias for html_escape :
A utility method for escaping HTML tag characters. Use this method to escape any unsafe content.
In Rails 3 and above it is used by default so you don't need to use this method explicitly
The best safe way is: <%= sanitize #x %>
It will avoid XSS!
In Simple Rails terms:
h remove html tags into number characters so that rendering won't break your html
html_safe sets a boolean in string so that the string is considered as html save
raw It converts to html_safe to string
Short and Simple
Let's assume we can't trust user input.
Bad:
user_input.html_safe # asking for trouble
Good:
user_input.html_escape # or
h(user_input) # in some view
Inputs we control:
trusted_input_only.html_safe
that should be fine. but be careful what your trusted inputs are. They must only be generated from your app.
i am new to ROR.. i am having a doubt in internationalization commands.
in some case we were using <%=t :str_use%>
and in some cases we were using <%= t(:str_use) %>
what is the difference between these two
when should i have to use 1st and when to use the second one..
Pls give some ideas regarding this.
i am having a view file with in that i am having lot of strings i wanna to internationalization them.
in some cases i am having like <td>Use</td>
and in some cases
<% if use %> Use <br />
<% else %>
This is ruby's syntax, not specifically ror ;)
Both are the same. Ruby can guess the parenthesis even if they're not there.
So it's completely up to you.
There's no difference between t :str and t(:str) — they both call the method t with the symbol :str as an argument. In Ruby, parentheses around arguments are optional.
But these are both different from t: str, which is Ruby 1.9 shorthand for the hash {:t => str}.
When to use t(:str)? When you want to chain further methods.
Try this in Rails:
t 'some.translation'.capitalize
t('some.translation').capitalize
First approach will return:
Translation
..as in the second half the identifier after the period, instead of translating the whole text. This, from what I can tell, is because you are passing the argument 'some.translation'.capitalize, not calling capitalize on the return, like the second example.