rails ruby iterate through partials in directory - ruby-on-rails

To those helping.. Thanks. Still no solution but getting closer. The errors i think are because my "file" evaluates to "app/views/main/show/_partial.html.erb". and render adds it's own relative path. So I guess i need to list the file names.. maybe a dir.foreach or dir.glob type command.. i'll keep digging. THANKS!
I have a directory full of partials I would like to call in a page. So I wrote a loop but it yields errors.
<% Dir["app/views/main/show/*"].each do |file| %>
<%= render #{file} %>
<% end %>
When I replace the render line with a simple file it lists the file names so i know the loop and Dir location work. The problem I THINK is that render is looking for a string. So I've tried all sorts of things from searching google and here like the #{file}, creating a variable first, raw,...etc.
also I think render may be looking in a different directory relative the Dir. I'll try out some stuff there to.
How should I be handling this? I'm up for switching from Dir to Dir.foreach or any other strategy that makes sense.
Thanks.
EDIT: Here's the solution I've implemented (directory path changed from above):
<% Dir["app/views/partials/show/*.html.erb"].each do |file| %>
<p> <%= render 'partials/show/' + File.basename(file,'.html.erb').slice!(1..-1) %></p>
<% end %>

file is already a string, so there is no need to escape. Also, you have to give the full path. This should work:
<% Dir["app/views/main/show/*"].each do |file| %>
<%= render :file => Rails.root.join(file).to_s %>
<% end %>
#{} only works inside double quotes. E.g. "#{file}", but in this case that's not necessary. You can just use file.

Related

Include html fragment if on one of a number of pages (Rails)

I have a pretty standard Rails 4 application at the moment with a number of static pages (home, about, contact etc) as well as the database backed pages. I want to include a html partial across most of the site but not on static pages (apart from the home page). I can get this working if I was stating just one page to exclude, for example the about page, using:
<% if !current_page?(about_url) %>
include the partial
<% end %>
I'm not sure how to write this to have a list of urls, i.e. about_url, contact_url etc. I tried something along the lines of:
<% if [about_url, contact_url, ...].!include? current_page
but maybe not surprisingly it didn't work.
Is there a way to achieve this within the erb itself without going back to the controller? (I'm thinking I'd have to create the array for each controller)
Thanks for any help.
-- Update --
I just tried (following the comment below):
<% if not [about_url, contact_url].include? request.original_url %>
<%= render partial %>
<% end %>
it doesn't appear to like this either. I'm not sure if my syntax if off again or it can't be done this way.
You can go about doing this in many ways, one of which can be:
<% if current_page?(controller: 'YOUR_CONTROLLER_NAME') &&
(current_page?(action: 'about') || current_page?(action: 'contact') || ... ) %>
include partial
<% end %>
I think it should work but your syntax is off.
<% if [about_url, contact_url, ...].!include? current_page
should be
<% if not [about_url, contact_url, ...].include? current_page
Or if you prefer (but I prefer "not" since it's more readable)
<% if ![about_url, contact_url, ...].include? current_page
However, for readability and testability you should perhaps put that logic in the application controller or in a helper.
Okay, thanks to the commenters I got it to work using the following:
<% if not [about_path, contact_path].include? request.path %>
<%= render 'layouts/minibar' %>
<% end %>
** the main points being to use *_path to compare against request.path.

Including the contents of a javascript file

If there a way to include the content of a javascript file into a Rails view?
I know about Ruby's File.read, but I'm searching for some helper already done.
<%= javascript_tag do %>
<%= render :file => '/path/to/rails/app/path/to/javascript.js' %>
<% end %>
So you can include any javascript code located on your machine. But to be honest there's more appropriate way to do that kind of things.

Block comments in html.erb templates in rails

How do you comment out html mixed with ruby code?
some text <% ... %> more text <%= ... %>
something else
<% ... %>
In jsp it's real simple: <%-- ... --%>, but I'm unable to find any concise option in rails.
Simple html comments <!-- ... --> do not work: ruby code is still executed and yells errors.
There's an option to use if false with html comments, but it's quite verbose, not to mention IDEs doesn't support it.
There's also an option coming from pure ruby, which surprisingly works.
<%
=begin %>
... html and ruby code goes here
<%
=end %>
It's generally fine, except that it's verbose, weird-looking and none of ruby IDEs I know support it (yep, I like to comment/comment-out with one keystroke).
I'm curious, is there any 'official' of doing this in rails?
Thanks!
Use this for commenting single lines:
<%# your_ruby_code %>
For multiple lines, the following would work:
<% =begin %>
<% ruby_code %>
<% =end %>
What you said would work.
I wouldn't count as a solution, but perhaps enclosing the chunk between an
<% if false %>
...
<% end %>
or if you feel a little dirty, create a helper that simply outputs nothing.
I've never needed it, but I'm stumbled there seems to be no out-of-the-box solution for this.
The =begin approach is annoying because:
It doesn't work for mixed HTML and Ruby (or just HTML) that's on a single line
It's annoying to type
The <% if false %> approach works, but it looks weird and doesn't give anyone else who looks at your code a hint about your intentions.
My solution is as follows:
In application_helper.rb, add a method so:
def comment
end
Then in your view template, you can say:
<% comment do %>Some stuff that won't be rendered...<% end %>
This works because any Ruby method can take a block, but will silently ignore the passed-in block if your method doesn't include a yield.
<%#=
...commented
multiline
block...
%>
For block comments in templates, my text editor (Komodo) finds this variation on #Garfield's recommendation least obnoxious:
<%# A long multiline comment in a rails template ...
# line 2
# and so on ...
# %>
To comment out erb tags use the ruby comment hash symbol before the = sign in the opening tag
<p>
This is some text I want to keep
<%= #some_object.some_attribute %>
</p>
<p>
I want to keep this text but comment out the erb tag
<%#= #some_object.another_attribute %>
</p>
<!--
<p>
I want all of this text commented out including the erb tag
<%#= #some_object.some_attribute %>
</p>
-->
<!--
<p>
I just want this html commented out but I want to keep the erb tag
<%= #some_object.some_attribute %>
</p>
-->
Since you can use <% %> to put a ruby block, it can be certainly used to put in comments into it.
A simpler and elegant solution would look like...
<%
# See! I am a Ruby Comment
# And I am multi-line
# I look like a recognizable ruby comment block too
# and not so complex
# The only drawback with me is the Hash symbol you have to repeat
# But it's the norm, isn't it?
%>
After =begin you do not need to put %>
<%
=begin
code code code code code code
code code code code code code
code code code code code code
code code code code code code
=end %>
Just an addendum to some of the previous answers. I found the =begin/=end solution most useful, but for the sake of beauty I write it like so:
<%
=begin
<p>HTML will be ignored</p>
<%= 'and so will ruby' %>
<p>
<%= 'plus the whole block will be greyed in editor' %>
</p>
=end
%>
Note that since everything is ignored until the =end there is no need to close the =begin tag with %> or open the =end tag with <% (which has also been pointed out in an earlier answer)
I found this to be the most elegant solution to completely outcomment a block of mixed ruby and html code and have it greyed out in my editor as well, as opposed to the <% if false %> solution. Only drawback is that =begin and =end must be placed at the very beginning of the line..
Use a HEREDOC called comment
Pros:
Self-explanatory that this is a comment
Works for erb and HTML tags
Has ok syntax highlighting (as one long string)
Cons:
Weird 3 line closing syntax
No keyboard shortcuts
Code:
The opening tag can be
<% <<-COMMENT %>
the above closing erb tag is just for looks (to match the end),
but don't put anything else there, it may show up on the page
or
<%
<<-COMMENT
%>
Anything here won't run or show up in the browser
<P>
this will not be displayed in the browser
<strong> even in the developer's tools </strong>
</p>
<% 1_000_000_000_000.times do |count| %>
for the <%= count %>'th time, this won't run a trillion times,
this is all just a string
all of these %>, <%, <% end %>, end, do, <!--, won't cause any issues.
but the below opening erb tag is important (if you used any erb tags in the comment).
I have no clue why?
The closing tag
yes it needs to be 3 lines 😟.
I don't know why the opening erb tag is important but it is! (unless you didn't use any erb tags in the comment).
<%
COMMENT
%>
You have to bear in mind where the code is executed. Ruby-style comments work because the Ruby code is executed on the server before it is served to the web browser. This also explains why HTML comments do not work—the Ruby has already been executed.
Doesn't the IDE you're using support creating custom macros for commenting out blocks of code?
You can use both <%if false%> and HTML comments at the same time:
<%if false%><--
stuff to comment out
--><%end%>
The benefits are:
Ruby code is not executed
The commented block has gray color in IDE
The intention is obvious for other developers
Sublime Text's block comment shortcut ctrl+shift+/ notices whether you've selected normal HTML or an Erb tag and puts either the <!--- or <%
=begin %> accordingly.
This is the onlyone that worked for me.
<%
=begin %>
code code code code code code
code code code code code code
code code code code code code
code code code code code code
=end %>
<% %w(
<span title="<%= title %>">hello</span>
) %>
I hope I've just blown your minds!
One way
This is my preferred way.
<%# START COMMENTED OUT SECTION %>
<%if false%><--
your view code here....
--><%end%>
<%# END COMMENTED OUT SECTION %>
You might say, why on earth would you want massive caps locks sentences in your code? The answer is because it's easy to forget (or simply not know) what <%if false%><-- is doing, or what --><%end%> is doing. A sleepy or uncaffeinated developer could easily delete them thinking they were typos, which would not be good! That's why I try to be kind to myself/other developers and make it super obvious. It's not succinct or pretty, but it's very practical and almost foolproof.
Second way
This method is great for being:
Simple
Not idiosyncratic (i.e. uses normally formatted ruby)
Expressive: conveys the meaning of what's happening (someone can easily figure out what it's doing)
Minimal
And here it is:
<%#
multiple
lines
commented
out
%>
The only acceptable solution I ever found to this back-breaking problem was to put a space within the "<%=" to make it no longer register as ruby code, and then comment out the whole block with html comments
Like this:
<!--
<p>
< %= #some_object.some_attribute %>
</p>
<p>
< %= #some_object.another_attribute %>
</p>
<p>
< %= #some_object.some_attribute %>
</p>
<p>
< %= #some_object.some_attribute %>
</p>
-->
Yes, adding the spaces is annoying. But it is the least annoying of all the solutions I've yet seen.

Netbeans Source Format: Can It Recognize Other Stuff? (For RoR Views)

I am in love with Netbeans Source->Format feature. Is there any way to get it to recognize stuff in these blocks
<% content_for :style do %>
<% end %>
as CSS? It would also help for autocomplete.
Ditto, of course, for
<% content_for :javascript do %>
<% end %>
blocks.
I'm not certain, but I think the source formatting is on a file basis only, not on parts of a file.
Edit: Actually, I'm wrong, the formatting can recognize various languages in the same file...obviously what's happening in an ERB file for ruby and html code. But I don't see a way of extending that.

on Rails, is there any way to output content besides the <%= %> tag?

it seems that on Rails or erb, the only way to output anything is by <%= %>
<% puts "hello" %> won't work, unlike PHP.
is there any other method at all?
concat will do:
<% concat ("wah ha ha!") %>
Reference:
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M001710
from the source code,
<% output_buffer << "hmm" %>
will work too and it is tested... but i think this is even lower level and should be avoided.
The conventional response object does exist under the covers, and you can call response.write(str). But a large part of the beauty of RoR is that this nuts and bolts stuff is abstracted away for you, and you don't have to do it.

Resources