Featured post
Mysterious Ruby Block behavior: &block vs. {block.call} -
when writing helper printing javascript can used both other helpers , views, stumbled upon following problem:
def javascript(print_tag = false, &block) content_for(:javascript) if print_tag javascript_tag(&block) # not work javascript_tag { block.call } # work else capture(&block) end end end this helper should called javascript { "alert('hurray'); }.
in first alternative - expected work - rails javascript_tag helper renders empty <script type="text/javascript"> //<![cdata[ //]]> </script> tag.
the second alternative, however, works expected.
what's going on there? how can different?
you doing on views, right?
<%= javascript { "alert('hurray');" } %> but content_tag(&block) work, should call javascript way content_tag intended used in views, is:
<% javascript %> alert('hurray'); <% end %> content_tag's behavior different depending on it's called from, see function block_called_from_erb? in source code. in first case function returns true because block come erb (and it's concated, don't want that!), in second returns false (you re-created block scratch) , content_tag returns string content, want.
# ./action_view/helpers/javascript_helper.rb tag = content_tag(:script, javascript_cdata_section(content), html_options.merge(:type => mime::js)) if block_called_from_erb?(block) concat(tag) else tag end - Get link
- X
- Other Apps
Comments
Post a Comment