Is it possible to call truncate method in rspec feature test? - ruby-on-rails-3

I'm using Rails 3.2, Rspec 2 and capybara 2.
I am truncating a string of body text in my webpage and would like to test this in my feature spec.
Can someone advise how to do this because I can't seem to call truncate in my test because it keeps saying it's an undefined method and I don't really want to have a long string of truncated text in my test suite; just applying the truncate function is good enough.
I've tried using helper.truncate(), view.truncate() but to no avail.
I've used the Faker gem in other parts of my tests if there's a way to generate a lorem ipsum string and truncate it to compare against somehow.
View code:
<dd><%= truncate(project.details, :length => 100) %></dd>`
Test code
it { should have_selector('dd', #project.details) }
This test test worked fine when I was showing the full details text but because I've decided to only show the first 100 characters in this view I'm not sure how to test for this without having to set the details as a fixed string and then check for a truncated version of it somehow.
Thanks
Col

truncate is a Rails extension to the String class and, as such, is not available in Ruby or RSpec. There may be way to "include" it in some fashion, but I'm familiar with how to do that. It turns out that the definition is self-contained, however, so defining it yourself is straightforward. Here is the source taken from http://apidock.com/rails/String/truncate. It's defined to an instance method, so if you want to use it with a string that's passed in, you'd need to include a text parameter in lieu of referencing self as is currently done in the first line of the body.
# File activesupport/lib/active_support/core_ext/string/filters.rb, line 38
def truncate(length, options = {})
text = self.dup
options[:omission] ||= "..."
length_with_room_for_omission = length - options[:omission].mb_chars.length
chars = text.mb_chars
stop = options[:separator] ?
(chars.rindex(options[:separator].mb_chars, length_with_room_for_omission) || length_with_room_for_omission) : length_with_room_for_omission
(chars.length > length ? chars[0...stop] + options[:omission] : text).to_s
end

This works for me :)
require 'active_support/core_ext/string/filters'
it { should have_selector('dd', #project.details.truncate(100)) }

In the end I decided that if the page was being viewed on a larger screen then the wider column would allow more of the details to be shown and reduce the need for truncating the text so I decided to trim the details using css instead to reduce what was shown onscreen using the following:
.text-trim {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}

Related

Displaying multiple errors (one per line) in asp-validation-for

ASP.NET Core 3.1
I have the following code in my View:
<span asp-validation-for="NewPassword" class="text-danger"></span>
If I type in a password, such as 'a', I get multiple errors back. I want to display them in that span ONE PER LINE.
In my Controller I have the following:
var descriptions = string.Empty;
foreach (var error in errors)
descriptions += error.Description + "<br />";
ModelState.AddModelError("NewPassword", descriptions);
But this does not translate the "br" tags and they get displayed as if they were part of one very long single error message.
Note: Adding them one at a time into the ModelState simply overwrites the previous, leaving only the last one displayed.
Instead of "br", i've tried HTMLString.NewLine and Environment.NewLine but none of these work. I could write a loop in my View, but is there a preferred way in ASP.NET Core?
So my question is: How can I put a new line between each description?
Instead of "br", i've tried HTMLString.NewLine and Environment.NewLine but none of these work.
That's because <br/> will be escaped by default. If you wish, you could use #Html.Raw() to generate the raw content without escaping the dangerous characters. But I don't think it's a good idea: there will be a high risk of XSS if you output a raw string directly.
By default, \r\n won't be displayed in browser. You need a CSS snippet to show a new line.
A much better way is to use the CSS to control the display style: add a style for the validation field in your *.css file:
span.field-validation-error{
white-space: pre-line;
}
And change the csharp code to use a \n as separator:
foreach (var error in errors)
descriptions += error.Description + "\n";
Demo :

Birt export in pdf does not wordwrap long lines

My reports preview is ok.
But now, I need to export to pdf...and I've got an issue : the content of some cells are truncated to the witdh of the column.
For instance, 1 cell should display "BASELINE"...in the preview it's ok...but in pdf, it displays "BASEL".
I've been looking for a solution the whole day and did not find anything...
Of course : I don't want to fit the width of the column on the length of this word "BASELINE" because the content is dynamic...
Instead, I want to fix the column width and then, the cell should display something like that :
BASEL
INE
Any idea ?
Thanks in advance (am a little bit desperated...)
The solution is trivial in BIRT v4.9 if you've integrated the engine into your java code. Just set the PDF rendering options.
RenderOption options = new PDFRenderOption();
options.setOutputStream(out);
options.setOutputFormat("pdf");
options.setOption(PDFRenderOption.PDF_WORDBREAK, true);
options.setOption(PDFRenderOption.PDF_TEXT_WRAPPING, true);
task.setRenderOption(options);
You have to set a special PDF emitter option:
PDFRenderOption options = new PDFRenderOption();
options.setOption(PDFRenderOption.PDF_HYPHENATION, true);
This is if you integrated BIRT into your Java program.
For the viewer servlet, it is possible to set such options, too, AFAIK, but I don't know how; maybe on the URL or using environment variables.
I had the same issue. I found a very good topic about that : http://developer.actuate.com/community/forum/index.php?/topic/19827-how-do-i-use-word-wrap-in-report-design/?s=173b4ad992e47395e2c8b9070c2d3cce
This will split the string in the given number of character you want :
The function to add in a functions.js (for example). To let you know, I create some folder in my report project : one for the reports, one for the template, one for the libraries, another for the resources, I added this js file in the resources folder.
/**
* Format a long String to be smaller and be entirely showed
*
*#param longStr
* the String to split
*#param width
* the character number that the string should be
*
*#returns the string splited
*/
function wrap(longStr,width){
length = longStr.length;
if(length <= width)
return longStr;
return (longStr.substring(0, width) + "\n" + wrap(longStr.substring(width, length), width));
}
You will have to add this js file in the reports : in the properties -> Resources -> Javascript files
This is working for me.
Note: you can add this function in your data directly if you need only once...
The disadvantage of this : you will have to specify a max length for your character, you can have blank spaces in the column if you specify a number to small to fill the column.
But, this is the best way I found. Let me know if you find something else and if it's working.

How to set value of text field all at once with a webdriver?

I am using Cucumber, watir-webdriver, page-object, and jruby. I am writing a method in a page class that enters a value into a text area. I am using a generated method in the page-object gem that, under the hood, invokes the Watir-Webdriver set method, that in turn invokes send_keys on the element.
Anyway, the problem for me is I am trying to add a VERY LARGE STRING (in order to test max size stuff for a validateable form object). It's 4000 characters and takes a noticeable amount of time to enter.
It would be great if there were a way to just paste the whole string into the text area at once. Is there any way to do this with the technologies I have on hand? These are..
JRuby, watir-webdriver, page-object (which really just delegates to watir-webdriver). I suppose under the hood it's selenium-webdriver that's doing the browser driver interaction in any case.
So far I haven't found a way around ultimately using send_keys which basically sends one key stroke at a time and that's why a huge character string is a pain.
You could directly set the value of the field using execute_script.
Given a page with a textarea:
<html>
<body>
<textarea></textarea>
</body>
</html>
Inputting the textarea with set took 6-9 seconds (with Firefox/Chrome):
input = 'a' * 4000
browser.textarea.set(input)
However, by using execute_script to directly set the value, it only took 0.2 seconds:
input = 'a' * 4000
field = browser.textarea
browser.execute_script('arguments[0].value = arguments[1];', field, input)

How to custom tag word(s) in GATE JAPE grammar?

I have a set of documents and each document has different heading. Example if document heading says "Psychological Evaluation" I want to tag the document as "Medicalrule".
I loaded the document and loaded ANNIE with defaults.
In Processing Resources > New > Jape Transducer
2.1 wrote the following code in the text document and saved it as .JAPE extension
CODE :
Phase: ConjunctionIdentifier
Input: Token Split
Rule: Medicalrule
(
({Token.string=="Psychological"})+({Token.string == " "})+ ({Token.string == "Evaluation"}):Meddoc({Token.kind=="word"})
)
-->
:Meddoc
{
gate.AnnotationSet matchedAnns= (gate.AnnotationSet) bindings.get("Meddoc"); gate.FeatureMap newFeatures= Factory.newFeatureMap();newFeatures.put("rule","Medicalrule");annotations.add(matchedAnns.firstNode(),matchedAnns.lastNode(),"CC", newFeatures);
}
Loaded the above created .JAPE file and reinitialized
After the application is run the Annotation Set does not show the tag !
Am I doing wrong somewhere ?It would be great if someone could help me on this.
Appreciate your time.
Thank you
I'm sure that there is no annotation like: Token.string == " ". Try to use a SpaceToken annotation instead.
Also, why not to try gazetteers instead of hardcoding of texts values in to JAPE code?
There are three issues I can see here.
First, as ashingel says, spaces are not represented as Token annotations - this is deliberate as in most cases you don't care about the spacing between words, only the words themselves.
Second, the trailing ({Token.kind=="word"}) means that the rule will only match when "Psychological Evaluation" is followed by another word before the end of the current sentence (because you've got Split in the Input line).
Third, you're only binding the Meddoc label to the "Evaluation" token, not to the whole match.
I would try and simplify the LHS of the rule:
Phase: ConjunctionIdentifier
Input: Token Split
Rule: Medicalrule
(
{Token.string=="Psychological"}
{Token.string == "Evaluation"}
):meddoc
and for the RHS (a) you don't need to do the explicit bindings.get because you've used a labelled block so you already have the bound annots available, (b) you should use outputAS instead of annotations, and (c) you should generally avoid the add method that takes nodes, as it isn't safe if the input and output annotation sets are different. If you're using a recent snapshot of GATE then the gate.Utils static methods can help you a lot here
:meddoc {
Utils.addAnn(outputAS, meddocAnnots,"CC",
Utils.featureMap("rule","Medicalrule"));
}
If you're using 7.1 or earlier then the addAnn method isn't available so it's slightly more convoluted:
:meddoc {
try {
outputAS.add(Utils.start(meddocAnnots), Utils.end(meddocAnnots),"CC",
Utils.featureMap("rule","Medicalrule"));
} catch(InvalidOffsetException e) { // can't happen, but won't compile without
throw new JapeException(e);
}
}
Finally, just to check, you did definitely add your new JAPE Transducer PR to the end of the pipeline?

Rails 3.1 html_safe (+ combo of string data) - making controller action fire twice?

I've been banging my head for the last two days trying to figure this out and I finally narrowed down the source.
I'm using a helper to generate the html for my sidebar and using html_safe on the return value. When I have the html structured just the right way, it causes my controller action to fire twice (I saw it first when I was getting two records inserted into my db from my action and then I verified using ruby-debug). Here's the helper code:
def get_sidebar
first = String.new
second = String.new
str = String.new
str+= "<a href=''><img src='" << first << second << "'></a>"
str.html_safe
end
If I modify str and remove the img tag from before and after the concat'd vars, it only fires once. If the concat'd vars aren't empty, it only fires once (these were originally coming out of non-nullable db columns but were empty strings). And if I don't call the html_safe method, it only fires once...
Any ideas what is going on here? Is this expected behavior for html_safe? Am I crazy?
Thanks in advance!
use content_tag instead of html_safe
When the user's browser loads a page with that string in it, what happens? It has to go back to the server to get the image. Two requests. Sounds like your image URL is actually a Rails request.
If you don't use html_safe to mark the string as safe, then the image tag will be escaped and the browser won't go back to the server.