Wrapping text into lines at word boundaries - ruby-on-rails

1) I want to auto wrap a text by words so that each line does not exceed 56 characters.
Is there a method for doing this, or do I need to roll my own?
#comment_text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
My view:
<%= #comment_text.cool_string_function( 56 ) %>
would render:
Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua.
2) I want to indent the text by 4 spaces so that:
<%= #comment_text.cool_string_function( {:width => 56, :indent => 4} ) %>
would render:
Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua.

I believe the function you are looking for is word_wrap. Something like this should work:
<%= word_wrap #comment_text, :line_width => 56 %>
You can combine that with gsub to get the indentation you desire:
<%= word_wrap(#comment_text, :line_width => 52).gsub("\n", "\n ") %>
But you should probably move that into a helper method to keep your view clean.

Perhaps word_wrap helper can help you.
To indent the text you can replace \n (newline) with newline + 4 spaces.

Related

Passing data through URL to the other application in Ruby on Rails

I am new to Ruby on Rails, I would like to pass some data to my other application. I am currently using httpparty gem but I am having a hard time when I send big data such as text so I was wondering if there is any recommended gem that converts plain html text to
the format that I can send through or easy way to do
What I am trying to do:
e.g:
def abc_action
contents = params[:content]
response = HTTParty.post("http://abc.go.com?contents=#{contents}")
end
say content params include many paragraphs such as
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"
Thanks for your help.
From what i can tel you're getting the "contents" from a POST request on your controller, which i'm guessing came from a form you created in one of your views. If that's the case you could skip the controller altogether and just point your form's action to http://abc.go.com. You can read about how to do it here.
<%= form_tag("http://abc.go.com", method: "post") do %>
<%= label_tag(:contents, "Contents: ") %>
<%= text_area_tag(:contents) %>
<%= submit_tag("Submit") %>
<% end %>
This way the user's browser sends the request and you don't need to have an HTTP client on your controller. It is important to know that you have to take care of the authenticity token by hand and set up abc to redirect back to your original app or wherever you want with http 302.
If abc is a rails app then the controller could look like this:
class SomeController < ApplicationController
protect_from_forgery except: :create
def create
#use strong params not params[:contents]
#something = SomeModel.new(contents: params[:contents])
if #something.save
format.html {redirect_to "http://original_url/place_to_go_after_content_submit")
end
end

Tablesorter stickyheaders inside jQuery UI tabs

I have run into some odd behavior using the Sticky Headers plugin from within a jQuery UI tabs widget. I have tried to attach the sticky header to a wrapper element inside the tab, but the positioning of the header is incorrect. It begins at the top of the widget and moves down as I scroll the table?
The following illustrates the problem. When selecting tab "Two" and scrolling the table, the header moves vertically within the widget.
http://jsfiddle.net/gws000/74ja6gdj/5/
<div id="tabs">
<ul>
<li><span>One</span></li>
<li><span>Two</span></li>
<li><span>Three</span></li>
</ul>
<div id="fragment-1">
<p>First tab is active by default:</p><span>test1</span>
<pre><code>$( "#tabs" ).tabs(); </code></pre>
</div>
<div id="fragment-2">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
<div id='mywrapper' style='height:200px;overflow-y:scroll;'>
<table class="tablesorter">
<thead>
<tr>
<th>AlphaNumeric</th>
<th class='filter-select'>Numeric</th>
<th>Animals</th>
<th>Sites</th>
</tr>
</thead>
<tbody>
<tr>
<td>abc 123</td>
<td>10</td>
<td>Koala</td>
<td>http://www.google.com</td>
</tr>
<tr>
<td>abc 1</td>
<td>234</td>
<td>Ox</td>
<td>http://www.yahoo.com</td>
</tr>
<tr>
<td>abc 9</td>
<td>10</td>
<td>Girafee</td>
<td>http://www.facebook.com</td>
</tr>
<tr>
<td>zyx 24</td>
<td>767</td>
<td>Bison</td>
<td>http://www.whitehouse.gov/</td>
</tr>
<tr>
<td>abc 11</td>
<td>3</td>
<td>Chimp</td>
<td>http://www.ucla.edu/</td>
</tr>
<tr>
<td>abc 2</td>
<td>56</td>
<td>Elephant</td>
<td>http://www.wikipedia.org/</td>
</tr>
<tr>
<td>abc 9</td>
<td>155</td>
<td>Lion</td>
<td>http://www.nytimes.com/</td>
</tr>
<tr>
<td>ABC 10</td>
<td>87</td>
<td>Zebra</td>
<td>http://www.google.com</td>
</tr>
<tr>
<td>zyx 1</td>
<td>999</td>
<td>Koala</td>
<td>http://www.mit.edu/</td>
</tr>
<tr>
<td>zyx 12</td>
<td>0</td>
<td>Llama</td>
<td>http://www.nasa.gov/</td>
</tr>
</tbody>
</table>
</div>
</div>
<div id="fragment-3">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.<span>test3</span>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</div>
</div>
$("#tabs").tabs({
activate: function (event, ui) {
var $t = ui.newPanel.find('table');
if ($t.length) {
if ($t[0].config) {
$t.trigger('applyWidgets');
} else {
$t.tablesorter({
theme: 'blue',
widgets: ["zebra", "filter", "stickyheaders"],
widgetOptions: {
stickyHeaders_attachTo: "#mywrapper"
}
});
}
}
}
});
Any help would be appreciated.
It looks like the issue is that the #mywrapper element is missing a position:relative; definition. The sticky header is using position:absolute, so it ends up getting its positioned calculated based on the #tabs element, which is the only parent element with a position:relative assigned (by the jQuery tabs widget) (updated demo).
<div id='mywrapper' style='height:200px;overflow-y:scroll;position:relative;'>

truncate text in homepage which has been posted using ckeditor in ruby on rails framework

I am using ckeditor with combination with carrierwave in textarea (https://github.com/galetahub/ckeditor). I am using ruby on rails as a framework.
I am trying to truncate article to display only a small section in homepage which has been published from backend using ckeditor. However since i have also uploaded image for the article using same ckeditor truncate is not working. And .html_safe is also not working showing me the html code instead of rendering it.
Code used in homepage to display only a small section using truncate function:
<% i=0 %>
<% #diplomacies.each do |diplomacy_article| %>
<% if i ==0 %>
<h3><a><%= diplomacy_article.title %></a></h3>
<p><%= truncate(diplomacy_article.article.html_safe, :length=>600) %> </p>
<% end %>
<% i=i+1 %>
<% end %>
Current Result in home page:
<p><img alt="" src="/uploads/ckeditor/pictures/2/content_pm.jpg" style="float:left; height:81px; margin-left:4px; margin-right:4px; width:100px" /> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error, nobis tempore, ad temporibus iure enim recusandae. Laborum ratione, accusamus quis amet recusandae tempora vitae? Reiciendis ab similique doloremque exercitationem saepe. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas vero voluptatem voluptatibus accusamus, doloremque aspernatur earum saepe repellat cupiditate architecto quidem hic ut tempora quod, dolore i...
Current problem line: <%= truncate(diplomacy_article.article.html_safe, :length=>600) %>
Current Controller index method:
def index
category_diplomacy= Category.where(["name=?", "Diplomacy"]).first
if category_diplomacy
#diplomacies=Article.where(["category_id=?","#{category_diplomacy.id}" ]).order("id DESC").limit(7).all
end
end
####### Response to the answer provided by: #Ruby Racer
Truncation does not seem to work. I have tried following code:
Thanks for the reply, however it did not worked for me.
I tried the following code, however truncate does not seem to work.
<% i=0 %>
<% #diplomacies.each do |diplomacy_article| %>
<% orig_text = diplomacy_article.article %>
<% img_text = orig_text.match(/<img.+(\/)?>/).to_s if orig_text.match(/<img.+(\/)?>/) %>
<% body_text = truncate(orig_text.gsub(/<.*>/,''), :length=>30) %>
<% if i ==0 %>
<h3><a><%= diplomacy_article.title %></a></h3>
<p><%= "#{img_text} #{body_text} ".html_safe %> </p>
<% end %>
<% i=i+1 %>
<% end %>
I have tried to output all of your suggested code.
1)Code:
<%= orig_text = diplomacy_article.article %>
Output:
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error, nobis tempore, ad temporibus iure enim recusandae. Laborum ratione, accusamus quis amet recusandae tempora vitae? Reiciendis ab similique doloremque exercitationem saepe. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas vero voluptatem voluptatibus accusamus, doloremque aspernatur earum saepe repellat cupiditate architecto quidem hic ut tempora quod, dolore incidunt rem maiores corporis!
2)
<%= img_text = orig_text.match(//).to_s if orig_text.match(//) %>
Output:
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error, nobis tempore, ad temporibus iure enim recusandae. Laborum ratione, accusamus quis amet recusandae tempora vitae? Reiciendis ab similique doloremque exercitationem saepe. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas vero voluptatem voluptatibus accusamus, doloremque aspernatur earum saepe repellat cupiditate architecto quidem hic ut tempora quod, dolore incidunt rem maiores corporis!
3)
<%= body_text = truncate(orig_text.gsub(/<.*>/,''), :length=>10) %>
Output:
{no output}
If I understand correctly, you want the image and you want the body text.Regular Expressions can do most of the work here:
EDIT
I have corrected the regex to create the image tag if it exists. So img_text will either contain an image tag or a blank string.
body_text is meant to contain everything except the html tags that once were there (with or without the <br>'s). This has also been edited.
So, what will basically be there is:
<%
orig_text = diplomacy_article.article
img_text = orig_text.match(/<img[^>]+>/).to_s
body_text = truncate(orig_text.gsub(/<[^>]+>/,''), :length=>600) # without br's
#or body_text = truncate(orig_text.gsub(/<[^([Bb][Rr])^>]+>/,''), :length=>600) # with br's
%>
And to output (sample html):
<div class="my_image">
<%= img_text.html_safe %>
</div>
<div class="my_abstract">
<%= body_text.html_safe %>
</div>
This should be working and img_text will output an image only if an image tag exists in the body.
Or you can also use like that:
<%
orig_text = diplomacy_article.article
body_text = truncate(orig_text,:length=>600, :omission => "" , :escape => false)
%>
And to output (sample html):
<%= body_text.html_safe %>

Rails Render Partial in Helper

I have been trying to render one of my partials in a helper function located within my controller.
The first issue I encountered was that the helper was returning the each loop instead of the result of the loop. To remedy this I attempted to have it return a string containing the results of the loop.
def display_replies(comment)
if comment.replies.count > 0
string = ""
comment.replies.each do |reply, index|
string = string + (render partial: "comment", locals: {index: index}).to_s.html_safe
end
string
end
Called in View with <%= display_replies(reply) %>
When I look at my view, what is returned and displayed is HTML, however it is escaped and thus plain text, it looks something like this:
["<div class='c comment'>\n<div class='profile'>\n<img src='/assets/profile_image_sample.jpg'>\n</div>\n<div class='message'>\n<div class='username'>Will Leach</div>\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus adipiscing purus et mi aliquet malesuada. Curabitur porttitor varius turpis eget sollicitudin. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut dapibus consectetur tortor, nec aliquet lacus tempus vitae. Sed felis massa, dapibus in arcu sit amet, rhoncus condimentum eros. Etiam rutrum lectus in malesuada aliquam. Mauris vitae diam vel felis accumsan vulputate vel nec tortor. Nunc pretium hendrerit est, ut cursus ipsum commodo sit amet.\n<div class='reply-link'>\n<a href='#'>Reply to Comment</a>\n</div>\n</div>\n</div>\n"]
I would simply like this to be regular unescaped HTML. I read somewhere that adding html_safe would fix this, but alas it hasn't.
Where to go from here?
Actually, html_safe should be used like this:-
<%= display_replies(reply).html_safe %>
To fix \n and [", we need to have .join after the loop. Like so:
Helper:
def display_replies(comment)
if comment.replies.count > 0
raw(
comment.replies.map do |reply, index|
render 'comment', index: index
end.join
)
end
end
View:
<%= display_replies(reply) %>
Note that I removed all html_safe and replaced with raw. And instead of each loop, I used map, so we don't have to create variable string and return it after the loop.
Hope this helps!
You can use the html_safe method like this
<%= html_safe display_replies(reply) %>

Truncate at Page Break CKeditor Rails

i have blog with ruby on rails and using ckeditor for editor text. I need to truncate my post at page break for printing from ckeditor.
example post beforetruncate
<p style="text-align: justify;">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<div style="page-break-after: always;">
<span style="display: none;"> </span></div>
<p style="text-align: justify;">Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
</p>
how do automatically truncate before save when it encounters this element?
<div style="page-break-after: always;">
<span style="display: none;"> </span></div>
post aftertruncate
<p style="text-align: justify;">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
on model
before_save :truncate_post
def truncate_post
self.aftertruncate = ......
end
thanks for help..

Resources