Im unsure how to use Maps with a template engine. Can someone tell me what im doing wrong here?
def engine = new groovy.text.SimpleTemplateEngine()
def binding = [jobs:[[name:'job1',action:'build'], [name:'job2', action:'build']]]
def text = '''
println ${jobs}
println ${jobs[0].name}
${jobs}.each{ job ->
println "name " + job.name
}
'''
def template = engine.createTemplate(text).make(binding)
println template
produces this output
Result
println [[name:job1, action:build], [name:job2, action:build]]
println job1
[[name:job1, action:build], [name:job2, action:build]].each{ job ->
println "name " + job.name
}
The 2nd println shows job1 from this ${jobs[0].name} which looks good except I want to do that in the iterator, but I'm not sure what that each is showing me. I would expect to get
name job1
name job2
from the iterator. Any ideas how to do this?
all from documentation: https://docs.groovy-lang.org/latest/html/api/groovy/text/SimpleTemplateEngine.html
def engine = new groovy.text.SimpleTemplateEngine()
def binding = [jobs:[[name:'job1',action:'build'], [name:'job2', action:'build']]]
def text = '''
jobs[0].name = ${jobs[0].name}
<% jobs.each{ job -> %>\
name = ${job.name}
<%}%>
'''
def template = engine.createTemplate(text).make(binding)
println template
result:
jobs[0].name = job1
name = job1
name = job2
Related
Tried this code but it wont return the expected output. The list that i have doesnt have single quote.
def curlCmd = sh(script: "<some curl cmd POST>", returnStdout:true).trim()
def parsedResponse = readJSON text: curlCmd
def response = parsedResponse['fruit']
// Output of response is [apple123, apple124, apple125]
def maxValue = response.max()
echo "maxValue: ${maxValue}"
Actual Output:
maxValue: []
Expected Output:
maxValue: [apple125]
This works fine:
def curlCmd = sh(script: "<some curl cmd POST>", returnStdout:true).trim()
def parsedResponse = readJSON text: curlCmd
def response = parsedResponse['fruit'] as ArrayList
// Output of response is [apple123, apple124, apple125]
def maxValue = Collections.max(response)
echo "maxValue: ${maxValue}"
Output:
maxValue: apple125
The data_get function retrieves a value from a nested array or object using "dot" notation:
$data = ['products' => ['desk' => ['price' => 100]]];
$price = data_get($data, 'products.desk.price');
// 100
More detail in Laravel Doc
I do this function:
def get_data(data, dot_path, default=None):
arr_paths = dot_path.split('.')
result = data
for path in arr_paths:
try:
if isinstance(result, (dict, list, tuple)):
result = result[path]
else:
result = None
except KeyError as e:
result = None
if not result:
result = default
return result
I am following this article to set the Order for sorting.
Excerpt from above article
class Language {
String name
boolean dynamic
String toString() { "name: $name, dynamic: $dynamic" }
}
def languages = [
new Language(name: 'Groovy', dynamic: true),
new Language(name: 'Java', dynamic: false),
new Language(name: 'Clojure', dynamic: true)
]
def list = ['name', 'dynamic']
sh = new GroovyShell()
closure = sh.evaluate("{ }")
def cList = list.collect { closure(it) }
println cList
// We order first on dynamic property and then name property.
def orderByDynamicAndName = new OrderBy([{ it.dynamic }, { it.name }])
Here, I would like to pass the list of closures dynamically from a list.
Say, there is a list and list may vary in element size in different applications / classes. This is main reason I wanted the dynamic closure list.
def list = ['name', 'dynamic']
From the above list, want to generate it as list of closure and pass it to OrderBy class as argument.
//Build closure list. But, not sure how to generate it from above list
def cList =
def orderByDynamicAndName = new OrderBy(cList)
Tried to refer this thread, but some how could not generate cList as desired
Tried to build cList as shown below; getting errors
def list = ['name', 'dynamic']
sh = new GroovyShell()
closure = sh.evaluate("{ fieldName -> \"it\".fieldName }")
def cList = list.collect { closure(it) }
Error:
Exception thrown
groovy.lang.MissingPropertyException: No such property: fieldName for class: java.lang.String
How to over come this?
class Language {
String name
boolean dynamic
String toString() { "name: $name, dynamic: $dynamic" }
}
def languages = [
new Language(name: 'Groovy', dynamic: true),
new Language(name: 'Java', dynamic: false),
new Language(name: 'Clojure', dynamic: true)
]
def list = ['dynamic', 'name']
def cList = list.collect{ propName-> { target-> target[propName] } }
def orderBy = new OrderBy(cList)
def sortedLanguages = languages.toSorted(orderBy)
println languages
println sortedLanguages
actually this expression
list.collect{ propName-> { target-> target[propName] } }
converts list of property names to list of closures
['dynamic', 'name'] => [ { target-> target['dynamic'] }, { target-> target['name'] } ]
and target is just a parameter name in the closure.
later, when we call sort, each closure { target-> target[propName] } will be called against an object in a sorting array and our closure returns the value by a property name.
After trial and error, below code worked for me in order to create the list of closures.
def list = ['dynamic', 'name']
def tempClosureString = list.collect { element -> "{it.$element}" }.join(',')
def cList = new GroovyShell().evaluate("[ $tempClosureString ]")
def orderByDynamicAndName = new OrderBy(cList)
I welcome if there are better alternatives.
I would like to know if it is possible to loop through a list of values in SimpleTemplateEngine groovy. For example:
def values = [ "1", "2", "3" ]
def engine = new groovy.text.SimpleTemplateEngine()
def text = '''\
???
'''
def template = engine.createTemplate(text).make(values)
println template.toString()
How can I get:
1
2
3
by changing the variable text?
def values = [ "1", "2", "3" ]
def engine = new groovy.text.SimpleTemplateEngine()
def text = '''<% values.each { println it} %>'''
println engine.createTemplate(text).make([values: values])
Did you mean?
def values = [ "1", "2", "3" ]
def engine = new groovy.text.SimpleTemplateEngine()
def text = '''
${values.each { println it} }
'''
println engine.createTemplate(text).make([values: values])
if you want an elegant template without many quotes and without a lot of imperative programming, you can do the following
def text = '''
<% for (item in values) { %>
<%= item %>
<% } %>
'''
The rule is simple:
Use <%= ..%> if there is rendering of value.
Use <% .. %> if there is flow control handling ( if/else, for loop,... )
I want to use UIPickerView to select a number and assign the selected number to a label. I worked out how to do it using the ib gem and using interface builder to create the initial interface and it works fine. However, I would like to do it purely using RubyMotion code and I can't for the life of me get it to work. The best I have managed is for the label to return True and not a number.
I'm using the following standard code for the picker view delegate methods:
def pickerView(pickerView, numberOfRowsInComponent:component)
101
end
def pickerView(pickerView, titleForRow:row, forComponent:component)
row.to_s
end
def numberOfComponentsInPickerView (pickerView)
1
end
def pickerView(pickerView, didSelectRow:row, inComponent:component)
end
def pickerView(pickerView, titleForRow:row, forComponent:component)
" #{row+1}"
end
def submit
totals.addTotals(myPicker.selectedRowInComponent(0))
end
and then the label text is populated like this:
numLabel = UILabel.new
numLabel.text = "Number Selected: #{submit}"
numLabel.font = UIFont.boldSystemFontOfSize(18)
numLabel.frame = [[20,320],[260,340]]
numLabel.numberOfLines = 2
numLabel.adjustsFontSizeToFitWidth = 'YES'
self.view.addSubview numLabel
The totals is a shared client.
Here is how to do it in RubyMotion alone. Note that the label and picker are set up in viewDidLoad. The label gets updated in pickerView:didSelectRow:inComponent:
app_delegate.rb
class AppDelegate
def application(application, didFinishLaunchingWithOptions:launchOptions)
#window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
#window.rootViewController = PickerDemo.new
#window.makeKeyAndVisible
true
end
end
picker_demo.rb
class PickerDemo < UIViewController
def viewDidLoad
view.backgroundColor = UIColor.whiteColor
#numLabel = UILabel.new
#numLabel.text = "Number Selected: 0"
#numLabel.font = UIFont.boldSystemFontOfSize(18)
#numLabel.frame = [[20,100],[260,120]]
#numLabel.numberOfLines = 2
#numLabel.adjustsFontSizeToFitWidth = true
view.addSubview(#numLabel)
#picker = UIPickerView.new
#picker.frame = [[0, 183], [320, 162]]
#picker.delegate = self
#picker.dataSource = self
view.addSubview(#picker)
end
def pickerView(pickerView, numberOfRowsInComponent:component)
101
end
def pickerView(pickerView, titleForRow:row, forComponent:component)
row.to_s
end
def numberOfComponentsInPickerView(pickerView)
1
end
def pickerView(pickerView, didSelectRow:row, inComponent:component)
#numLabel.text = "Number Selected: #{row}"
end
end