rspec for solr search: less_than / greater_than scenarios - rspec-rails

I am writing controller spec for solr search.
This is my controller
#search = Plan.available_plans.search do
fulltext params[:zip_code] do
end
all_of do
with :status, "active"
with(:price).greater_than(10)
with(:end_date).greater_than Time.now
end
And the spec is :
it "should list active plans" do
get :index
Sunspot.session.should be_a_search_for(Plan)
Sunspot.session.should_not have_search_params(:with, :status, "inactive")
end
it "should not list plans with price < 10" do
get :index
Sunspot.session.should be_a_search_for(Plan)
Sunspot.session.should_not have_search_params(:with, :price, :less_than => 10)
end
it "should not list plans that have expired" do
get :index
Sunspot.session.should be_a_search_for(Plan)
Sunspot.session.should_not have_search_params(:with, :end_date, :less_than => Date.today)
end
The first one works fine. I searched a lot but could not find a proper syntax that would work to test other scenarios. Plz help me out.

Related

Crystal parser creates an ASTNode that should be Crystal::Expressions at runtime but is somehow a Crystal::Nop

require "compiler/crystal/syntax"
s = "a = 5; puts a + 3"
nodes = Crystal::Parser.parse(s)
puts nodes.class # => Crystal::Expressions
puts nodes.is_a? Crystal::Expressions # => true
puts nodes.is_a? Crystal::Nop # => false
puts nodes.expressions
So, I would assume the last expression to give an Array (or an ArrayLiteral node). However, I get
undefined method 'expressions' for Crystal::Nop (compile-time type is Crystal::ASTNode+)
Which makes no sense. .class and .is_a? are runtime checks, so the nodes , which has a compile-time type of ASTNode should be Crystal::Expressions, not Crystal::Nop.
The behaviour is the same on crystal versions 0.25.0, 0.25.1, 0.26.0, 0.26.1 and the version currently on the master branch of the git repo.
The error is raised at compile time because not all subclasses of Crystal::ASTNode have #expressions method. Crystal::Nop just happens to be the first such subclass the compiler checks and subsequently decides to throw an error. The way to fix the code is:
require "compiler/crystal/syntax"
s = "a = 5; puts a + 3"
nodes = Crystal::Parser.parse(s)
case nodes
when Crystal::Expressions
puts nodes.expressions
when Crystal::Nop
puts "It's a nop"
else
puts "Unhandles case for #{nodes.class}"
end
Alternatively, you can force the compiler to assume it's Crystal::Expressions by using .as:
nodes.as(Crystal::Expressions).expressions
Credit for this answer goes to straight-shoota on this Github issue

Rails conditional CSS in view helper

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) %>

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.

Get words out of a file in Ada

I have a folder with files containing some text. I am trying to go through all the files one after the other, and count how many times we see every word in the text files.
I know how to open the file, but once I'm in the file I don't know how to read each word one after the other, and go to the next word.
If anyone has some ideas to guide me it'd be great.
Read the file a line at a time into a string using Get_Line, then break the line up into the individual words.
Here's one way of doing it, I needed some playtime with the containers.
Using streams is still the best solution for your problem, given the multiple files.
Text_Search.ads
Pragma Ada_2012;
With
Ada.Containers.Indefinite_Ordered_Maps;
Package Text_Search with Elaborate_Body is
Text : Constant String :=
ASCII.HT &
"We hold these truths to be self-evident, that all men are created " &
"equal, that they are endowed by their Creator with certain unalienable "&
"Rights, that among these are Life, Liberty and the pursuit of " &
"Happiness.--That to secure these rights, Governments are instituted " &
"among Men, deriving their just powers from the consent of the governed" &
", --That whenever any Form of Government becomes destructive of these " &
"ends, it is the Right of the People to alter or to abolish it, and to " &
"institute new Government, laying its foundation on such principles " &
"and organizing its powers in such form, as to them shall seem most " &
"likely to effect their Safety and Happiness. Prudence, indeed, will " &
"dictate that Governments long established should not be changed for " &
"light and transient causes; and accordingly all experience hath shewn, "&
"that mankind are more disposed to suffer, while evils are sufferable, " &
"than to right themselves by abolishing the forms to which they are " &
"accustomed. But when a long train of abuses and usurpations, pursuing " &
"invariably the same Object evinces a design to reduce them under " &
"absolute Despotism, it is their right, it is their duty, to throw off " &
"such Government, and to provide new Guards for their future security." &
"now the necessity which constrains them to alter their former Systems " &
"of Government. The history of the present King of Great Britain is a " &
"history of repeated injuries and usurpations, all having in direct " &
"object the establishment of an absolute Tyranny over these States. To " &
"prove this, let Facts be submitted to a candid world.";
Package Word_List is New Ada.Containers.Indefinite_Ordered_Maps(
Key_Type => String,
Element_Type => Positive
);
Function Create_Map( Words : String ) Return Word_List.Map;
Words : Word_List.map;
End Text_Search;
Text_Search.adb
Package Body Text_Search is
Function Create_Map( Words : String ) Return Word_List.Map is
Delimiters : Array (Character) of Boolean:=
('.' | ' ' | '-' | ',' | ';' | ASCII.HT => True, Others => False);
Index, Start, Stop : Positive := Words'First;
begin
Return Result : Word_List.Map do
Parse:
loop
Start:= Index;
-- Ignore initial delimeters.
while Delimiters(Words(Start)) loop
Start:= 1+Start;
end loop;
Stop:= Start;
while not Delimiters(Words(Stop)) loop
Stop:= 1+Stop;
end loop;
declare
-- Because we stop *on* a delimiter we mustn't include it.
Subtype R is Positive Range Start..Stop-1;
Substring : String renames Words(R);
begin
-- if it's there, increment; otherwise add it.
if Result.Contains( Substring ) then
Result(Substring):= 1 + Result(Substring);
else
Result.Include( Key => substring, New_Item => 1 );
end if;
end;
Index:= Stop + 1;
end loop parse;
exception
When Constraint_Error => null; -- we run until our index fails.
end return;
End Create_Map;
Begin
Words:= Create_Map( Words => Text );
End Text_Search;
Test.adb
Pragma Ada_2012;
Pragma Assertion_Policy( Check );
With
Text_Search,
Ada.Text_IO;
Procedure Test is
Procedure Print_Word( Item : Text_Search.Word_List.Cursor ) is
use Text_Search.Word_List;
Word : String renames Key(Item);
Word_Column : String(1..20) := (others => ' ');
begin
Word_Column(1..Word'Length+1):= Word & ':';
Ada.Text_IO.Put_Line( Word_Column & Positive'Image(Element(Item)) );
End Print_Word;
Begin
Text_Search.Words.Iterate( Print_Word'Access );
End Test;
Instead of going by individual words, you could read the file a line at a time into a string using Get_Line, and then use regular expressions: Regular Expressions in Ada?
If you're using Ada 2012 here's how I would recommend doing it:
With Ada.Containers.Indefinite_Ordered_Maps.
Instantiate a Map with String as key, and Positive as Key;
Grab the string; I'd use either a single string or stream-processing.
Break the input-text into words; this can be done on-the-fly if you use streams.
When you get a word (from #4) add it to your map if it doesn't exist, otherwise increment the element.
When you are finished, just run a For Element of WORD_MAP Loop that prints the string & count.
There's several ways you could handle strings in #3:
Perfectly sized via recursive function call [terminating on a non-word character or the end of input].
Unbounded_String
Vector (Positive, Character) -- append for valid characters, convert to array [string] and add to the map when an invalid-character [or the end of input] is encountered -- working variable.
Not Null Access String working variable.

How do I traverse a collection in classic ASP?

I want to be able to do:
For Each thing In things
End For
CLASSIC ASP - NOT .NET!
Something like this?
dim cars(2),x
cars(0)="Volvo"
cars(1)="Saab"
cars(2)="BMW"
For Each x in cars
response.write(x & "<br />")
Next
See www.w3schools.com.
If you want to associate keys and values use a dictionary object instead:
Dim objDictionary
Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.Add "Name", "Scott"
objDictionary.Add "Age", "20"
if objDictionary.Exists("Name") then
' Do something
else
' Do something else
end if
Whatever your [things] are need to be written outside of VBScript.
In VB6, you can write a Custom Collection class, then you'll need to compile to an ActiveX DLL and register it on your webserver to access it.
The closest you are going to get is using a Dictionary (as mentioned by Pacifika)
Dim objDictionary
Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.CompareMode = vbTextCompare 'makes the keys case insensitive'
objDictionary.Add "Name", "Scott"
objDictionary.Add "Age", "20"
But I loop through my dictionaries like a collection
For Each Entry In objDictionary
Response.write objDictionary(Entry) & "<br />"
Next
You can loop through the entire dictionary this way writing out the values which would look like this:
Scott
20
You can also do this
For Each Entry In objDictionary
Response.write Entry & ": " & objDictionary(Entry) & "<br />"
Next
Which would produce
Name: Scott
Age: 20
One approach I've used before is to use a property of the collection that returns an array, which can be iterated over.
Class MyCollection
Public Property Get Items
Items = ReturnItemsAsAnArray()
End Property
...
End Class
Iterate like:
Set things = New MyCollection
For Each thing in things.Items
...
Next
As Brett said, its better to use a vb component to create collections. Dictionary objects are not very commonly used in ASP unless for specific need based applications.
Be VERY carefully on using VB Script Dictionary Object!
Just discover this "autovivication" thing, native on this object: http://en.wikipedia.org/wiki/Autovivification
So, when you need to compare values, NEVER use a boolen comparison like:
If objDic.Item("varName") <> "" Then...
This will automatically add the key "varName" to the dictionary (if it doesn't exist, with an empty value) , in order to carry on evaluating the boolean expression.
If needed, use instead If objDic.Exists("varName").
Just spend a few days knocking walls, with this Microsoft "feature"...
vbscript-dictionary-object-creating-a-key-which-never-existed-but-present-in-another-object

Resources