Rails conditional CSS in view helper - css

I have a simple rails app and I'm trying to write a view helper that does the following.
Compares two values. If the current_month amount is greater than the forecast amount then make the text green. If the current_month amount is less than the forecast amount then make the text red.
I wrote out this simple helper to append text to the output of the the rails method, but I'm unsure of how to inject CSS/styling into this.
def target_hit(forecast, current)
(if current.amount > forecast.amount
number_to_currency(current.amount.to_s) + " Yay"
elsif current.amount < forecast.amount
number_to_currency(current.amount.to_s) + " No dice"
end).html_safe
end
I'm pretty proficient on the backend but when it comes to front-end stuff I'm stumbling a lot. Any help would be greatly appreciated.
example view code
<p class='total'>Current: <%= target_hit(#forecast, #current) %></p>

The rails helper content_tag http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag, is useful and means you don't have to use html_safe. I try to move all the logic from the views to helpers to make the view easy to read e.g.
def target_hit(current_amt, forecast_amt)
content_tag(:p, "#{number_to_currency(current_amt.to_s)} target_content(current_amt, forecast_amt)", class: "total #{target_class(current_amt, forecast_amt)}")
end
def target_content(current_amt, forecast_amt)
forecast_reached?(current_amt, forecast_amt) ? "Yay" : "No dice"
end
def target_class(current_amt, forecast_amt)
forecast_reached?(current_amt, forecast_amt) ? "green" : "red"
end
def forecast_reached?(current_amt, forecast_amt)
current_amt >= forecast_amt
end
in the view, you just call the helper method
<%= target_hit(#current.amount, #forecast.amount) %>

Related

WXPYTHON - Button Press Event

I have the following code - which is started by a button - say button1 which has to happen every one second -through a thread.
self.pump_rpm_text_control.AppendText(str(self.sheet_num.cell_value(self.sel+1,10)*(SortAndDecode(self.data, 'FrqQ5'))/65536))`
The problem I am facing here is - the "self.sel" is recorded from an excel sheet - when a selection from an excel sheet happens.
So I decided to write an if condition something like this:
if not self.OnList():
self.pump_rpm_text_control.AppendText("000")
else:
self.sheet_num.cell_value(self.sel + 1, 10)
self.pump_rpm_text_control.AppendText(str(self.sheet_num.cell_value(self.sel+1,10)*(SortAndDecode(self.data, 'FrqQ5'))/65536))
OnList - is the event that is called when a selection is being made on a listbox. But however my code is still going to ELSE, even though my OnLIST event has not happened. Any help would be greatly appreciated.
In the same way that this code follows the else path?
>>> def Onlist():
... return True
...
>>> if not Onlist():
... print False
... else:
... print True
...
True
It all depends on what value Onlist returns as furas commented

Primefaces datatable, nested conditional row coloring

I'm using PF 3.4.1 and JSF.
I would like to have a conditional selection of the css rowclass depending on two conditions:
One style should be for objects that are disabled, and one for objects that are expired.
I was able to put this two conditions in the same time, but, obviously, this cause a redundancy of css classes. I would like to have an overwrite of the classes in order to have predominance of the css class of disabled objects on expired objects.
Should look like this structure:
if (expired){
if (disabled){
return css1;
}
return css2
}
However, that is the code:
<p:dataTable id="results" var="utente" value="#{searchController.userList}"
paginator="true" rows="10"
rowStyleClass="#{user.expDate le user.currentDate ? 'rowdatatable3' : 'rowdatatable2'} #{user.enabled eq 'FALSE' ? 'rowdatatable1' : 'rowdatatable2'}"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="10,25,50">
rowdatatableX are css styles.
With this code, results have always rowdatatable2 or rowdatable1 and never the 3rd option.
My idea was something like this:
rowStyleClass="#{user.expDate le user.currentDate ? #{user.enabled eq 'FALSE' ? 'rowdatatable1' : 'rowdatatable3'} : 'rowdatatable2'} "
..but it doesn't work.
Please help to find a solution. Thanks.
Try writing a method in your Bean (or transient method in user entity) that compares 2 dates expDate and currentDate
public boolean isExpired() {
return getExpDate.before(getCurrentDate);
}
If user.enabled is of type boolean skip the FALSE comparison. Since your table variable is utente you should use it! Your expression should look like that
"#{utente.expired ? (utente.enabled ? 'rowdatatable1' : 'rowdatatable3') : 'rowdatatable2'}"
so:
IF expired AND enabled -> 'rowdatatable1'
IF expired AND disabled -> 'rowdatatable3'
IF NOT expired -> 'rowdatatable2'

Ruby on Rails: Retrieve css element and check value

I think this is a pretty straight forward question so I'll get to it:
subject.rb
def current_step
#current_step || steps.first
end
def steps
if #title = 'Baseline'
%w[sfmfa phq whoqol_bref positive_negative mses_self pam spsir change_questionnaire prosthesis cognitive comorbidity pain mspss audit ]
elsif #title = 'Treatment Completion'
%w[smfa phq whoqol_bref positive_negative pam spsir ssscq prosthesis pain complications mspss audit ptcs accessing_resources satisfaction ]
else
redirect_to #subjects_path
flash[:notice] = "Did not find title"
end
end
I'm trying to check the value of the Title element on my tc.html.erb webpage (this should return 'Treatment Completion'). At the moment the check isn't working, and I end up with the steps defined under 'Baseline' every time.
I have steps for a paginated form, and it all works for the Baseline page, so now I'm trying to pass a different set of elements as the steps definition for a different page.
I think I'm using the wrong accessor (#title). This ruby I'm using to provide the Title is:
<% provide(:title, 'Baseline') %>
Any input would be appreciated.
Well there are a couple of things that are wrong. The first thing is that you're trying to use redirect_to in a model. This should be used in a controller. Second, #subjects_path is not an instance variable, it's a url helper, so that should not have an # sign before it. Third, you're assigning, not comparing the if statement (using = and not ==).
So, to answer the original question, you could fix your original problem by:
def steps
if #title == 'Baseline'
%w[sfmfa phq whoqol_bref positive_negative mses_self pam spsir change_questionnaire prosthesis cognitive comorbidity pain mspss audit]
elsif #title == 'Treatment Completion'
%w[smfa phq whoqol_bref positive_negative pam spsir ssscq prosthesis pain complications mspss audit ptcs accessing_resources satisfaction]
else
redirect_to #subjects_path
flash[:notice] = "Did not find title"
end
end
Note that that only fixes the third error.

Watir, Page-objects: how to get all elements that have the same identifier

I have the following code code on my page I wanna check:
...
<p class="tags-link">
test1
test2
test3
</p>
....
<p class="tags-link">
test4
test5
test6
</p>
....
I use Watir-webdriver and page-object. And I need to get all links related to blocks with "tags-link" class.
I have the following code:
element(:tags, :p, :css => "tags-link a")
tags_element returns the 1st link only.
The following code will give me just 3 links related to the 1st block:
element(:tags, :p, :css => "tags-link")
tags_element.element.links.each do |elm|
puts elm
end
But I need to get all tags blocks
Now I have the following code that works, but I wanna be "page-object" oriented :
#browser.elements(:css =>".tags-link a").each do |tag|
puts tag
end
Could you please help me...to get all links on the page related to "tags-link" using page-objects
Thanks,
Anna
You can define a collection of links in your page object using links:
class MyPage
include PageObject
links(:tag_link, :css =>".tags-link a")
end
This will create a collection_name_elements method that returns an array of matching page-object elements. You can iterate over it to perform an action on each element. For example, to output the text of each link:
page.tag_link_elements.each do |link|
puts link.text
end
#=> test1
#=> test2
#=> test3
#=> test4
#=> test5
#=> test6
This is all you need to do:
ary_of_tests = #browser.ps(:class, 'tag-links').map do |t|
t.as.map do |x|
x.text
end
end
=> [["test1", "test2", "test3"], ["test4", "test5", "test6"]]
If you do not like dynamic arrays you can always use the flatten method to make it one dimensional or to_s method to make it into a string. Defining a new class and specifying scenarios seems like overkill to me, but to each his own.
Note: ps(:class, 'tag-links) is a collection of all p elements with attribute class and value tag-links in the DOM of a given page.

How to use ? : if statements with Razor and inline code blocks

I'm updating my old .aspx views with the new Razore view engine. I have a bunch of places where I have code like this:
<span class="vote-up<%= puzzle.UserVote == VoteType.Up ? "-selected" : "" %>">Vote Up</span>
Ideally I'd like to do this:
<span class="vote-up#{puzzle.UserVote == VoteType.Up ? "-selected" : ""}">Vote Up</span>
However there's two problems here:
vote-up#{puzzle.UserVote .... is not treating the # symbol as a start of a code block
#puzzle.UserVote == VoteType.Up looks at the first part #puzzle.UserVote as if it's supposed to render the value of the variable.
Anyone know how to address these issues?
This should work:
<span class="vote-up#(puzzle.UserVote == VoteType.Up ? "-selected" : "")">Vote Up</span>
#( condition ? "true" : "false" )
The key is to encapsulate the expression in parentheses after the # delimiter. You can make any compound expression work this way.
In most cases the solution of CD.. will work perfectly fine. However I had a bit more twisted situation:
#(String.IsNullOrEmpty(Model.MaidenName) ? " " : Model.MaidenName)
This would print me " " in my page, respectively generate the source &nbsp;. Now there is a function Html.Raw(" ") which is supposed to let you write source code, except in this constellation it throws a compiler error:
Compiler Error Message: CS0173: Type of conditional expression cannot
be determined because there is no implicit conversion between
'System.Web.IHtmlString' and 'string'
So I ended up writing a statement like the following, which is less nice but works even in my case:
#if (String.IsNullOrEmpty(Model.MaidenName)) { #Html.Raw(" ") } else { #Model.MaidenName }
Note: interesting thing is, once you are inside the curly brace, you have to restart a Razor block.

Resources