I was reading a blog post and saw a groovy snippet that looked lik
while ( entry = inputStream.nextEntry ) {
// do something
}
In the while loop, is this groovy syntax that will cause the loop to break when entry is null?
Yes, but it will probably make the compiler complain about
a possible accidental assignment. A better practise is:
while ((entry = inputStream.nextEntry )!=null) {}
First week using Groovy and wanted to test this out. Thought I would share the test & results. Thanks for pointing this out.
def list = ['one', 'two', null, 'four']
def it = list.iterator()
def i
while (i = it.next()) {
println i
}
Result: one
two
Related
I want to mock this function:
def self.set_segment_info(segment_info, history_record)
history_record.segment_info = segment_info
end
In my test, I want a mock that only confirms that I called set_segment_info with an expected value. I don't care about what I pass in for history_record.
How would I do this? I tried
SegmentHistoryRecord.expects(:set_segment_info).with(:segment_info => expected_segment_info, :history_record => anything)
But that doesn't work.
I ran into this today and ended up doing something like:
SegmentHistoryRecord.expects(:set_segment_info).with(
expected_segment_info,
anything
)
I find it more readable that the do version and it helped me avoid a rubocop issue with too many parameters.
Here's an implementation where, if your function takes a lot of parameters, it's more convenient to specify a value for just the one you care about, instead of for all of them:
expected_segment_info = # ...
SegmentHistoryRecord.expects(:set_segment_info).with() { |actual_parameters| actual_parameters[:segment_info] == expected_segment_info }
(Where, as in the original question, set_segment_info is the function being mocked, and segment_info is the parameter whose value you want to match. Note that the history_record parameter -- and any others that might be present -- don't need to be included.)
SegmentHistoryRecord.expects(:set_segment_info).with() do |param1, param2|
# change below to your verification for :segment_info
# and leave param2 doing nothing, the expectation will ignore param2
param1 == expected_segment_info
end
My question model holds the prompt and the answer choices for questions that students can answer. It includes columns named :choice_0, :choice_1, :choice_2, :choice_3, :choice_4, and :choice_5.
In one section of my controller, I've used the following code:
correct_array.push(these_params[:choice_0]) if !these_params[:choice_0].blank?
correct_array.push(these_params[:choice_1]) if !these_params[:choice_1].blank?
correct_array.push(these_params[:choice_2]) if !these_params[:choice_2].blank?
correct_array.push(these_params[:choice_3]) if !these_params[:choice_3].blank?
correct_array.push(these_params[:choice_4]) if !these_params[:choice_4].blank?
correct_array.push(these_params[:choice_5]) if !these_params[:choice_5].blank?
In other areas of my app, I've used the #{} syntax, for example:
params[:choice_#{n}]
But that doesn't work within a params hash for some reason. I'm sure that there is a drier way to accomplish these five lines.
Thank you in advance for any insight.
A more Ruby way to do this is:
correct_array = (0..5).map { |i| these_params["choice_#{i}".to_sym] }.select(&:present?)
Or as a method:
def correct_array
(0..5).map { |i| these_params["choice_#{i}".to_sym] }.select(&:present?)
end
In either case, you have the added bonus of not having to initialize correct_array as it is created on the fly.
You may try this
(0..5).each do |i|
param_i = these_params["choice_#{i}".to_sym]
correct_array.push(param_i) if param_i.present?
end
I am new to Ruby, so let me describe the context of my problem first:
I have a json as input which has the following key / value pair:
{
"service": "update"
}
The value has many different values for example: insert,delete etc.
Next there is a method x which handles the different requests:
def x(input)
case input[:service]
services = GenericService.new
when "update"
result = services.service(UpdateService.new,input)
when "insert"
result = services.service(InsertService.new,input)
when "delete"
result = services.service(DeleteService.new,input)
....
....
else
raise "Unknown service"
end
puts JSON.pretty_generate(result)
end
What is bothering me is that I still need to use a switch statement to check the String values (reminds me of 'instance of' ugh..). Is there a cleaner way (not need to use a switch)?
Finally I tried to search for an answer to my question and did not succeed, if however I missed it feel free to comment the related question.
Update: I was thinking to maybe cast the string to the related class name as follows: How do I create a class instance from a string name in ruby? and then call result = services.services(x.constantize.new,input) , then the class names ofcourse needs to match the input of the json.
You can try something like:
def x(input)
service_class_name = "#{input[:service].capitalize}Service"
service_class = Kernel.const_get(service_class_name)
service_class.new(input).process
end
In addition you might want to check if this is a valid Service class name at all.
I don't understand why you want to pass the service to GenericService this seems strange. let the service do it's job.
If you're trying to instatiate a class by it's name you're actually speaking about Reflection rather than Polymorphism.
In Ruby you can achieve this in this way:
byName = Object.const_get('YourClassName')
or if you are in a Rails app
byName= 'YourClassName'.constantize
Hope this helps
Just first thoughts, but you can do:
eval(services.service("#{input[:service].capitalize}Service.new, #{input})") if valid_service? input[:service]
def valid_service?
w%(delete update insert).include? input[:service]
end
As folks will no doubt shout, eval needs to be used with alot of care
I'm trying this thing for a while but can't figure out what am I doing wrong.
Here is sample function (which is similar to the original one, except for the hash, which is generated dynamically in the original one):
module Puppet::Parser::Functions
newfunction(:am_running_oss, :type => :rvalue ) do |args|
oss = {:linux=>["Slackware", "RedHat", "Caldera"],
:mac=>["Jaguar", "Lion", "Tiger", "Kodiak"],
:win=>["Chicago", "Daytona", "Longhorn"]}
cls = args[0]
if oss.key?(cls)
return oss[cls][0]
else
return 'undefined'
end
end
end
and then in my manifest, I have this:
$h= am_running_oss($::am_os_type)
notify { "=*=*= amRunningOS <|:|> ${h} =*=*=*=*=*=*=*=": }
(am_os_type is a fact, that returns win, mac or linux based on the node type)
I was expecting to see Jaguar or Slackware as the return value but I get undefined instead. Does anyone know what am I doing wrong? Is there anything still am I missing in terms of passing the args to the function? Cheers!!
Replying to my own question, in case google lands someone here looking for the same. The thing worked for me is to is define cls like this:
cls = args[0].to_sym if args[0].is_a? String
Cheers!!
I am new to groovy.I am reading values for 2 variables from console with below lines of code.
System.in.withReader {
println "Version: "
version = it.readLine()
println "Doc Type:"
Doc=it.readLine()
call getBillID(version,Doc)
}
getBillid method is as below,
def getBillID(int version,int doc)
{
allNodes.BillID.each {
theregularExpression=/\d+_\d+_\d+_\d_\d+_\d+_\d_${version}_${Doc}_\d+_\d+/
if(it != "" && it =~ theregularExpression) {
println "******" + it
}
}
}
now i want to use those variable values in my getBILLID method but i am getting error as
No signature of method: ReadXML.getBillID() is applicable for argument types: (java.lang.String, java.lang.String) values: [9, ]
where i went wrong.can any one tell me plz..
In addition to #Kalarani's answer, you could also do this:
System.in.withReader {
print "Version: "
int version = it.readLine() as int
print "Doc Type: "
int doc = it.readLine() as int
getBillID( version, doc )
}
As an aside; I would be careful with your capitalisation and variable names, ie: you have a variable called Doc with a capital letter. This is not the standard naming scheme, and you are best using all lowercase for variable names. You can see where it has got confused in the getBillID method. The parameter is called doc (all lowercase), but in the regular expression you reference ${Doc} (uppercase again).
This sort of thing is going to end up causing you a world of pain and bugs that might take you longer to find
Where is the getBillId() method defined? and what is the signature of the method? It would help understanding your problem if you could post that.