Accessing properties in templates by their name - templates

given the following pieces of code:
groovy:
binding = [key1: "val1"]
def f = new File('test.template')
engine = new GStringTemplateEngine()
template = engine.createTemplate(f).make(binding)
println template.toString()
test.template:
<% keyName = "key1" %>
Is there a way to access val1 by keyName in test.template?
This:
${ binding[keyName] }
does not work (No such property: key1 for class: groovy.lang.Binding). Any ideas? Maybe the name of the map holding the properties is different?
I know I could just write:
${ key1 }
but I need to access property key1 using variable keyName.

Not sure if this is better but I got the following to work (somewhat)
Map binding = [ keyName: 'key1', key1: "val1", m: [key1:'val100', key2:'val2']]
def f = new File('test.template')
def engine = new groovy.text.GStringTemplateEngine()
def template = engine.createTemplate(f).make(binding)
println template.toString()
with the following template:
$keyName
$key1
<%= m[keyName] %>
But this relies on a submap that holds the values you are looking for.
I can see scenarios where in the binding, you pass a list of fields you want to process or display (rather than knowing them ahead of time), so you would have to get the field names from a well-known variable and then process the others possibly thru a submap.

Related

Nested structured search is Sourcegraph?

I would like to search Java annotations with another annotations inside. I don't know how many nested levels there are or I don't want to specify it. Finally, I would like to search for examples of #ApiImplicitParams with param type body and with #Example annotations inside.
But first I am trying to match anything nested.
First I searched for
#ApiImplicitParams(...)
and it found me somethind. The very first result is
#ApiImplicitParams({ #ApiImplicitParam(name = "foo", value = "List of strings", paramType = "body", dataType = "Foo") })
and has #ApiImplicitParam inside. Let's try to match it.
I tried
#ApiImplicitParams({#ApiImplicitParam(...) ...})
but it didn't find that case with one nesting and didn't find any cases with multiple #ApiImplicitParams inside.
How to accomplish?
Finally, I would like to search for examples of #ApiImplicitParams with param type body and with #Example annotations inside.
I believe the following query will meet your requirements here.
#ApiImplicitParams({...#ApiImplicitParam(...paramType = "body"...)...}) lang:Java
Some examples of matches --
#ResponseBody
#ApiImplicitParams({ #ApiImplicitParam(name = "foo", value = "List of strings", paramType = "body", dataType = "Foo") })
public Foo create(#RequestBody final Foo foo) {
nickname = "setLoggingSettings")
#ApiImplicitParams({
#ApiImplicitParam(
name = "Logging Config",
value = "Logging config to be updated",
required = true,
dataType = "com.yugabyte.yw.forms.PlatformLoggingConfig",
paramType = "body")
})
public Result setLoggingSettings() throws JoranException {
A note on this --
I don't know how many nested levels there are or I don't want to specify it.
The query provided above assumes one nested block, I'm afraid right now Sourcegraph doesn't have a good way to express an arbitrary level of nesting.
Hope that helps!

OCaml/reason design modules

I'm coming from a Javascript background & I'm trying to understand how I need to structure/build a program with Reason/Ocaml's module system.
As an exercise let's say I want to write this piece of javascript in OCaml/Reason (will compile it back to js through js_of_ocaml)
var TeaType = new GraphQLObjectType({
name: 'Tea',
fields: () => ({
name: {type: GraphQLString},
steepingTime: {type: GraphQLInt},
}),
});
How should I design my program to accomplish this?
Should I make a module which takes another module to produce a GraphQLObjectType in js through js_of_ocaml?
How would I structure this type that backs a GraphQLObjectType?
Tea.re
let name = "Tea";
let fields = /* what type should I make for this? Tea is
just one of the many graphql-types I'll probably make */
I mean fields is a thunk which returns a map that contains an unknown amount of fields. (every graphqlobject has different fields)
To what type does this map in OCaml/Reason, do I need to make my own?
Just for you to feel the flavor of OCaml, the direct (syntactic) translation would be:
let tea_type = GraphQL.Object.{
name = "Tea";
fields = fun () -> QraphQL.Field.[{
name = GraphQL.Type.{name : GraphQL.string }
steeping_time = GraphQL.Type.{name : QraphQL.int }
}]
}
Basically, I mapped js objects to OCaml's records. There are also objects in OCaml with methods and inheritance, but I think that records are still a closer abstraction. The records can be seen as a named tuple, and, of course, can contain functions. Modules, are more heavy weight abstractions, that is also a collection of fields. Unlike records, modules may contain types, other modules, and basically any other syntactic construction. Since types are removed at compile time, the runtime representation of a module is absolutely the same as the representation of records. Modules also define namespaces. Since OCaml records are defined by the names of their fields, it is always useful to define each records in its own module, e.g.,
module GraphQL = struct
let int = "int"
let string = "string"
module Type = struct
type t = {
name : string
}
end
module Field = struct
type t = {
name : string;
steeping_time : Type.t
}
end
module Object = struct
type t = {
name : string;
fields : unit -> Field.t list
end
end

A proper way to separate concerns?

My app allows the users to manage their documents. When creating one, a user has to either enter the document content manually or select a file from their computer (which would convert many formats to HTML for the user).
Currently, I have a simple FileUploaderView which is basically an <input type="file"> that listens to file changes, and updates the value property of the view with an object like { file: { type: SOME_TYPE' }, content: SOME_CONTENT }.
Then, DocumentsNewController listens to changes in it and converts supported files to HTML, and puts the result into the document body.
However, doing it this way feels simply wrong and does not allow for simple reuse (which I want to be able to do).
App.DocumentsNewController = Ember.ObjectController.extend
# ... stuff ...
handleDocumentUpload: (->
doc = #get 'documentUpload'
return unless doc
Ember.run =>
#set 'uploadError', false
#set 'unsupportedFile', false
#set 'processingUpload', true
type = doc.file.type
text = ''
try
if type.match /^text\//
text = doc.content
# Convert new lines to br's and paragraphs
text = '<p>' + text.replace(/\n([ \t]*\n)+/g, '</p><p>').replace('\n', '<br />') + '</p>'
else if type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
text = new DOCX2HTML(doc.content).convert()
else
#set 'unsupportedFile', true
catch error
#set 'uploadError', true
finally
#set 'text', text
Ember.run => #set 'processingUpload', false
).observes 'documentUpload'
And the template is something like
... stuff ...
{{view App.FileUploaderView valueBinding="documentUpload" accept="text/*"}}
What would be the proper way to refactor file converting stuff out of the controller?
I want to be able to do something like:
{{documentHandler resultBinding="documentUpload"}}
and in controller
App.DocumentsNewController = Ember.ObjectController.extend
# ... stuff ...
handleDocumentUpload: (->
if doc = #get 'documentUpload'
#set 'text', doc
).observes 'documentUpload'
My first thought was to make a DocumentHandlerView which would display the input field, show the spinner, show the errors, parse the document and assign the result to result (and since controller's template has resultBinding="documentUpload", the HTML would trigger the controller's observer).
Using a view for that would allow for easier reuse but I still feel it's not the view's job to parse the document.
Is there a better way?
After reading closely your question the best thing that comes in mind would be to create a Ember.Mixin and then use it for all the controllers that need the same functionality.
Example taken from the ember API docs:
App.Editable = Ember.Mixin.create({
edit: function() {
console.log('starting to edit');
this.set('isEditing', true);
},
isEditing: false
});
// Mix mixins into classes by passing them as the first arguments to
// .extend.
App.CommentView = Ember.View.extend(App.Editable, {
template: Ember.Handlebars.compile('{{#if isEditing}}...{{else}}...{{/if}}')
});
commentView = App.CommentView.create();
commentView.edit(); // outputs 'starting to edit'
The example is only conceptual, but it will be easy to create a mixin yourself and put all the common logic in there.
Hope it helps.

How to pass parameters via the selector/action?

Is there a way to pass parameters via the addTarget call as it calls another function?
I've also tried the sender method - but that seems to break as well. What's the correct way to pass the parameters without creating global variables?
#my_button = UIButton.buttonWithType(UIButtonTypeRoundedRect)
#my_button.frame = [[110,180],[100,37]]
#my_button.setTitle("Press Me", forState:UIControlStateNormal)
#my_button.setTitle("Impressive!", forState:UIControlStateHighlighted)
# events
newtext = "hello world"
#my_button.addTarget(self, action:'buttonIsPressed(newtext)', forControlEvents:UIControlEventTouchDown)
view.addSubview(#my_button)
def buttonIsPressed (passText)
message = "Button was pressed down - " + passText.to_s
NSLog(message)
end
Update:
OK, here's a method with an instance variable that worked.
#my_button = UIButton.buttonWithType(UIButtonTypeRoundedRect)
#my_button.frame = [[110,180],[100,37]]
#my_button.setTitle("Press Me", forState:UIControlStateNormal)
#my_button.setTitle("Impressive!", forState:UIControlStateHighlighted)
# events
#newtext = "hello world"
#my_button.addTarget(self, action:'buttonIsPressed', forControlEvents:UIControlEventTouchDown)
view.addSubview(#my_button)
def buttonIsPressed
message = "Button was pressed down - " + #newtext
NSLog(message)
end
The easiest way of attaching "parameters" to a rubymotion UIButton call is through the use of tags.
First set up a button with a tag attribute. This tag is the parameter you want to pass to the target function.
#button = UIButton.buttonWithType(UIButtonTypeRoundedRect)
#button.setTitle "MyButton", forState:UIControlStateNormal
#button.frame =[[0,0],[100,50]]
#button.tag = 1
#button.addTarget(self, action: "buttonClicked:", forControlEvents:UIControlEventTouchUpInside)
Now create a method that accepts sender as a parameter:
def buttonClicked(sender)
mytag = sender.tag
#Do Magical Stuff Here
end
Forewarning: As far as I know, the tag attribute only accepts integer values. You could get around this by putting your logic into the target function like this:
def buttonClicked(sender)
mytag = sender.tag
if mytag == 1
string = "Foo"
else
string = "Bar"
end
end
Initially I tried setting the action with action: :buttonClicked which worked but did not allow for using the sender method.
Yes, you usually create instance variables in your Controller class, and then just call methods on them from any method.
According to the documentation using setTitle is the general way to set a title of a UIButton instance. So you're doing it right.

Persisting domain model w/ list of enums not working in GORM/Grails

My model needs to have multiple enums of the same type:
class Broker {
static constraints = {
brokerTypes(nullable:false)
}
List<BrokerType> brokerTypes
}
The model is being instantiated with the params from the request, which has in it a list of BrokerTypes:
def save(){
def brokerInstance = new Broker(newParams)
System.out.println(brokerInstance.getBrokerTypes().toString());
if (!brokerInstance.save(flush: true)) {
render(view: "create", model: [brokerInstance: brokerInstance])
return
}
redirect(action: "show", id: brokerInstance.id)
}
The println prints out the list of BrokerTypes as expected, so i know that it exists in the instance. Later, the model is retrieved as follows:
def brokerInstance = Broker.findByLatAndLon(lat,lon)
System.out.println(brokerInstance.getBrokerTypes().toString());
This time the println prints out 'null'
So i imagine the problem is that GORM doesn't know how to store this list of enums, and instead when the brokerInstance.save() is called, its saving the brokerTypes field as null.
Do i need to create a mapping somehow to get GORM to recognize the list? A hack alternative would be to instead of storing the list of enums, to store a list of strings or something and then map back to the enum when needed, but this doesnt seem clean
You will have to use a hasMany clause so that grails/gorm initializes a one to many relationship
You should add the following snippet to your domain class.
static hasMany = [brokerTypes : BrokerType]