Import html to rails method (in helper.rb) - html

I need piece of code for couple of times, and to follow DRY method (don't repeat yourself) i want to escape using this piece and retyping it for 5 times or more. So I want to define method what will contain both ruby and html, and ruby in html and js to, code. But I have problems with realization.
My html.erb look like this:
<% div_count = 1 %>
<div>
<% for post in #posts %>
<div class="post-on-main-page-<%= div_count %>"
id="js-count-<%= div_count_for_js %>">
<script>
$("#js-count-<%= div_count_for_js %>").click(function(){
window.location.href = "<%= post_url(post) %>";
});
</script>
<%= image_tag(post.picture.url) %>
<span><h5><%= post.theme %></h5></span>
</div>
<% end %>
<% div_count += 1 %>
<% if div_count == 4 %>
<% div_count = 1 %>
<% end %>
</div>
And I want create method, I think in application_helper.rb will do with this piece of code. What will look something like that:
def method_name(parameter)
<% div_count = 1 %>
<div>
<% for post in parameter %>
<div class="post-on-main-page-<%= div_count %>"
id="js-count-<%= div_count_for_js %>">
<script>
$("#js-count-<%= div_count_for_js %>").click(function(){
window.location.href = "<%= post_url(post) %>";
});
</script>
<%= image_tag(post.picture.url) %>
<span><h5><%= post.theme %></h5></span>
</div>
<% end %>
<% div_count += 1 %>
<% if div_count == 4 %>
<% div_count = 1 %>
<% end %>
</div>
end
The result what I want for html.erb
<%= method_name(#posts)%>
How can I make this to work?

You can move this code to some html. And when you want to use it, you just call render method.
<%= render 'html_file' %>

Related

Rails use content_for and render the same layout twice

I am using a theme that has very specific layouts and I wanted to make a failsafe way to you rails forms.
I have a layout app/views/shared/forms/fields/_layout.html.erb
<div class="js-form-message mb-4">
<div class="js-focus-state input-group u-form">
<div class="input-group g-brd-primary--focus">
<%= yield(:field) %>
</div>
</div>
</div>
And I have two partials.
1-st partial: app/views/shared/forms/fields/_email.html.erb
<% form = locals[:form] %>
<% locals[:required] = locals[:required].nil? ? true : locals[:required] %>
<% locals[:placeholder] = locals[:placeholder] || t('forms.shared.email.placeholder') %>
<%= render layout: "shared/forms/fields/layout", locals: locals do %>
<% content_for(:field) do %>
<%= form.email_field :email,
placeholder: locals[:placeholder],
class: "form-control g-py-15 g-px-15",
"data-error-class"=>"u-has-error-v1-3",
"data-success-class"=>"u-has-success-v1-2",
"data-msg-email" => t('forms.shared.email.validate'),
"data-msg" => t('forms.shared.required'),
autofocus: locals[:autofocus],
required: locals[:required] %>
<% end %>
<% end %>
2-nd partial: app/views/shared/forms/fields/_login.html.erb
<% form = locals[:form] %>
<% locals[:required] = locals[:required].nil? ? true : locals[:required] %>
<% locals[:placeholder] = locals[:placeholder] || t('forms.shared.login.placeholder') %>
<%= render layout: "shared/forms/fields/layout", locals: locals do %>
<% content_for(:field) do %>
<%= form.email_field :login,
placeholder: locals[:placeholder],
class: "form-control g-py-15 g-px-15",
"data-error-class"=>"u-has-error-v1-3",
"data-success-class"=>"u-has-success-v1-2",
"data-msg" => t('forms.shared.required'),
autofocus: locals[:autofocus],
required: locals[:required] %>
<% end %>
<% end %>
And when I do this:
<%= render "shared/forms/fields/email", locals: {form: f} %>
<%= render "shared/forms/fields/login", locals: {form: f} %>
I get
Email Field
Email Field/Login Field
I found out that content_for 'appends' the block that you give it and then when I yield the whole block is returned.
The first time there is nothing in content_for(:field) and it appends to it Email Field. But the second time it does not clear its content and just appends Login Field to it.
I am thinking of adding additional complexity to layout.html.erb so just keeping it inline isn't an option.
Is there a way to tell to the layout only to yield the 'newest' value of content_for.
EDIT:
I wrote a method to flush after an yield, suggesting that the same key would be used again:
def yield_and_flush!(content_key)
view_flow.content.delete(content_key)
end
content_for has flush option to reset previous content:
<% content_for :field, flush: true do %>
new content here
<% end %>
The solution was this to write an yield_and_flush! method. I saw the solution here
def yield_and_flush!(content_key)
view_flow.content.delete(content_key)
end

Separating posts in a newsfeed using CSS/BootStrap

I'm currently trying to render a newsfeed, similar to that of FB on a Rails application I'm working on. Unfortunately, I'm not the greatest when it comes to CSS and I'm having some issues trying to display different posts. This issue occurs whether I'm using BootStrap or plain CSS. I do believe it's something to do with the loop that is created by <% #posts.each do |post| %> Currently, whenever a new post is made, it wraps inside the previous post; thus the more posts that are made, the thicker the border gets.
Image:
<% if #posts.any? %>
<% #posts.each do |post| %>
<div class="well">
<%= post.user.first_name %> <%= post.user.last_name %><br>
<% if !post.image.exists? %>
<h2> <%= post.text %> </h2>
<% else %>
<h2> <%= link_to post.text, post_path(post) %> </h2>
<%= link_to post_path(post) do %>
<p><%= image_tag post.image.url(:medium) %></p>
<% end %>
<% end %>
<% if #user %>
<% if current_user.voted_up_on?(post) %>
<%= link_to "Like", dislike_post_path(post), method: :put %>
<% else %>
<%= link_to "Like", like_post_path(post), method: :put %>
<% end %>
<% end %>
<%= "Likes: #{post.get_upvotes.size}" %>
<% if post.user == current_user %>
<%= link_to "Edit", edit_post_path(post) %>
<%= link_to "Delete", post_path(post), method: :delete %>
<% end %>
<div id='comments_div' class="comments-index">
<%= render post.comments %>
</div>
<% if current_user %>
<%= form_for [post, post.comments.new ], remote: true do |f| %>
<%= f.text_area :text, placeholder: 'Add a comment' %>
<%= f.submit 'Comment' %>
<% end %>
<% else%>
<p>You need to <%= link_to "sign in", new_user_session_path %> to comment</p>
<% end %>
<% end %>
<% else %>
No posts have been added!
<% end %>
</div>
Any help would be greatly appreciated! Thanks.
Edit: OK, please take a look at the new image -- hopefully that will make the issue slightly more obvious. Additionally, I've removed all the dead tags and replaced them with just one: BootStrap's 'well' class. So, there you have it. All the information you need is within the code above.
from your description it sounds as though an html element is not being properly closed. Run the page source through an html validator and that could show you the problem.
If you don't want to take a structured problem solving approach, try adding another </div> to the end of your posts-index container.
Your issue is very simple, just that its not clear due to poor indendation.
A simple way to explain what you did is:
<-- if (start) -->
<-- do (start) -->
<-- post (start) -->
(post is not ending here, hence it breaks the layout)
<-- do (end) -->
<-- if (end) -->
<-- post (end) -->
Mistake in the above should be simple to understand so if you move your last </div>(of the well class) just before the second last <% end %>(of the <% #posts.each do |post| %> loop) it should fix the issue. So the last few lines should be
<% else%>
<p>You need to <%= link_to "sign in", new_user_session_path %> to comment</p>
<% end %>
</div>
<% end %>
<% else %>
No posts have been added!
<% end %>
Sounds to me like it could be a misplaced
<% end %>
or a missing
</div>
that is causing this behavior.
Proper indentation will point to where to close off actions or divs

If i pluck 2 values, how can i read them in html ruby

In my controller i find a uniq notebook and user name.
but i want to be able to check in my html code that it shows only one type of user.
in controller
def index
#allnotebooks = Note.uniq.pluck(:string, :notebook)
#notes = Note.all
end
in my html
<% #allnotebooks.each do |notebook| %>
<% if notebook.string == c_user.name %>
<option><%= notebook %></option>
<% end %>
<% end %>
notebook.string does not work. what am i missing
Also you can do in different way other than using pluck, using select you can do it
like-
In controller code-
def index
#allnotebooks = Note.uniq.select([:string, :notebook])
#notes = Note.all
end
in your html
<% #allnotebooks.each do |notebook| %>
<% if notebook.string == c_user.name %>
<option><%= notebook %></option>
<% end %>
<% end %>
Thanks!!!
Pluck returns an array.
Try notebook.first or notebook[0]
Docs here: http://apidock.com/rails/ActiveRecord/Calculations/pluck
Second example at the bottom applies here.
In your example it should be:
<% #allnotebooks.each do |notebook| %>
<% if notebook[0] == c_user.name %>
<option><%= notebook[1] %></option>
<% end %>
<% end %>
btw you might want to improve this by only loading notebooks where the string equals your user's name.
I am not a good ruby guy, You can write it like
<% #allnotebooks.each_with_index do |notebook, index| %>
<%= notebook[index].string %> => <%= notebook[index].notebook %>
<% end %>
for "a" unique notebook, you do you need to loop it?
just to say:
#allnotebooks.each{|notebook| <%= notebook[0] %> <%= notebook[1] %> }
But there can be better ways.

Some HTML for values of Hash keys

I am building a panel with a partial, but I'd like to customise the inside of the panel with some html. Is there any way to write some HTML for a hash value?
I have a custom partial _panel_builder.html.erb that I takes as argument pclass, heading, body, etc., that I would like to use like this :
(The below syntax is bad, but I don't really understand how I could do something nice..)
<% #etudes.each_with_index do |etude, i| %>
<%= render 'shared/panel_builder',
pclass: panel_color_rotation(i),
heading: etude.name,
# For the body param, I'd like to be able to use some HTML with occasional <%=...%> for variables, like :
body: (%>
<p><%=etude.description %></p>
<ul>
<%etude.competences.each do |comp| %>
<li><strong><%= competence.name %></strong> : <%=competence.level %>
<br><small><%=competence.why %></small>
</li>
<% end %>
</ul>
<%).html_safe,
collapsable: true %>
<% end %>
EDIT : An idea of what my _panel_builder partial looks like :
<%
collapsable ||= false
pclass ||= "default"
footer ||= false
%>
<div class="panel panel-<%= pclass %> <%= if collapsable then "panel-collapsable " end %>">
<div class="panel-heading">
<%= heading %>
<% if collapsable %>
<span class="pull-right"><i class="glyphicon glyphicon-chevron-down"></i></span>
<% end %>
</div>
<div class="panel-body <%= if collapsable then "collapse" end %>">
<%= body %>
</div>
<% if footer %>
<div class="panel-footer <%= if collapsable then "collapse" end %>">
<%= footer %>
</div>
<% end %>
</div>
Okay so I was actually looking for the capture helper :
<% #etudes.each_with_index do |etude, i| %>
<%= render 'shared/panel_builder',
pclass: panel_color_rotation(i),
heading: etude.name,
body: capture do %>
<p><%=etude.description %></p>
<ul>
<%etude.competences.each do |comp| %>
<li><strong><%= competence.name %></strong> : <%=competence.level %>
<br><small><%=competence.why %></small>
</li>
<% end %>
</ul>
<% end %>,
collapsible: true %>
<% end %>
Note : in some cases, I also want to pass a complex HTML block as the header of footer, so I can't just have a helper that takes a block.
Note2 : My panel is a HTML template made for generic data. I cannot pass it a Ruby object

constructing HTML with recursive loop in ruby on rails

Hello guys I have array of hashes:
#buttons = [{:serno=>1, :parent_serno=>0, :name=>"Home"},
{:serno=>2, :parent_serno=>0, :name=>"Search"},
{:serno=>3, :parent_serno=>0, :name=>"Search Payment"},
{:serno=>4, :parent_serno=>1, :name=>"Problematic Search Payment"},
{:serno=>5, :parent_serno=>1, :name=>"Cash Error"},
{:serno=>6, :parent_serno=>2, :name=>"Payment Note"},
{:serno=>7, :parent_serno=>2, :name=>"Search Payment By Category"},
{:serno=>8, :parent_serno=>3, :name=>"Search Payment New"},
{:serno=>9, :parent_serno=>3, :name=>"User Mangement"}]
I want to create div for each array hash (for example hash x) that's "parent_serno == 0", write their name inside the div and create another div inside of it, for every array hash that's "parent_serno == hash x [:serno]".
I tried to create partial:
<% for m in #buttons %>
<% unless #parent.present? %>
<% if m[:parent_serno] == 0 %>
<div>
<%= m[:name] %>
<% #parent = m[:serno] %>
<% if #buttons.find{ |b| b[:parent_serno] == #parent }.present? %>
<% #buttons.find{ |b| b[:parent_serno] == #parent }.each do %>
<%= render partial: "navbar", object: #parent %>
<% end %>
<% end %>
</div>
<% end%>
<% else %>
<% if m[:parent_serno] == #parent %>
<div>
<%= m[:name] %>
<% #parent = m[:serno] %>
<% if #buttons.find{ |b| b[:parent_serno] == #parent }.present? %>
<% #buttons.find{ |b| b[:parent_serno] == #parent }.each do %>
<%= render partial: "navbar", object: #parent %>
<% end %>
<% end %>
</div>
<% end%>
<% end %>
<% end %>
and render it in a another html.erb document, but apparently it just doesn't work :(
It only gives me the name of the first hash in the array and recursion stops there I guess.
I think the partial you need should look something like this:
_button.html.erb
<div>
<%= button[:name] %>
<% render partial: 'button',
collection: #buttons.select { |b| b[:parent_serno] == button[:serno] } %>
</div>
index.html.erb
...
<% render partial: 'button',
collection: #buttons.select { |b| b[:parent_serno] == 0 } %>
...