I've created some utilities that help me at generating HTML and I reference them in my views as #div( "class" -> "well" ){ Hello Well. }. Until now those classes were subclassing NodeSeq because they aren't escaped then. But I need to get rid off the NodeSeq in the top of my class hierarchy because Scala's xml is flawed and makes my code hacky and because I could switch to Traits then.
So I tried to find out how to prevent Play from escaping my Tag-objects. But unfortunately the only valid solution that I found is to override the template compiler and have the user specify my compiler in his Build.scala settings.
But I hopefully have overlooked a way more simple approach?
If your html helpers returns 'Html' rather than String you don't need to wrap them using the #Html tag in the view.
eg
import play.api.templates.Html
def a(src: String, value: String) : Html = Html(s"<a href='$src'>$value</a>")
Would be called in the view as below without needing to wrap in #Html
#a("www.example.com", "Example")
Since version 2.2.0-M1 there appeared a new approach in the docs that explains how to add custom formats to the template engine. This allows me to easily integrate my utilities.
Custom Template Format: Java, Scala
Related
I am very new at Scala and Spark area, and I found a strange grammar usage in the scala inside the Apache beam project and I can't understand.
Here is the strange place:
JavaDStream<Metadata> metadataDStream = mapWithStateDStream.map(new Tuple2MetadataFunction());
// register ReadReportDStream to report information related to this read.
new ReadReportDStream(metadataDStream.dstream(), id, getSourceName(source, id), stepName)
.register();
From the above code, you can see inside the constructor of ReadReportDstream, the first parameter is
metadataDStream.dstream()
If we go inside the dstream() method, you will see the following code:
class JavaDStream[T](val dstream: DStream[T])(implicit val classTag: ClassTag[T])
extends AbstractJavaDStreamLike[T, JavaDStream[T], JavaRDD[T]] {
I am wondering why it uses "metadataDStream.dstream()" in the constructor instead of "metadataDStream.dstream"? What does the "()" do?
It's mostly a question of convention. Methods with empty parameter lists are evaluated for their side-effects. Methods without parameters are assumed to be purely functional, and free of side-effects. You can read more about that here - https://docs.scala-lang.org/style/method-invocation.html (Arity-0 section)
So in that case, we're probably having some side-effects in metadataDStream.dstream(). However, syntactically writing it as metadataDStream.dstream won't be an error.
Is it possible to generate the with... type method with IntelliJ for Scala?
Example:
case class Person(name: String, age: Int)
I would like to find the tool to auto-generate the method of type:
def withName(name: String): Person = this.copy(name=name)
def withAge(age: Int): Person = this.copy(age=age)
is it possible?
Thank you.
There is no such thing out-of-the-box, but you can create a scala template of your own:
Select Settings/Preferences | Editor | Live Templates.
From options on the right, open the list of Scala templates.
Click + to add a new template.
You can see an example here
I you want to auto-generate these methods rather than writing them explicitly (even with an IntelliJ template), you can do that with an annotation macro that will run at compile-time.
In particular, you can check the scalameta project for informations about this. Note however that macros are an experimental feature that is likely to change in trivial ways when Scala 3 is released. In my opinion, you should think hard about whether writing withName(name) rather than copy(name=name) is worth the trouble of defining all these methods (whether its manually, through IntelliJ snippets, or using macros), and only go for macros if it will save you a lot of trouble down the line.
I have been looking for a while for a tern.js plugin that would allow me to use simple inline type annotations like this:
var f = function(/* string */ a) { ... }
This is a simple style that, for instance, Brackets supports.
I am aware that I can use JSDoc plugin with tern.js, but that requires a little more verbose syntax, that is especially difficult to use in anonymous functions.
Can I make JSDoc plugin parse these simple annotations or is there another plugin for that?
At my work we use a typical heavy enterprise stack of Hibernate, Spring, and JSF to handle our application, but after learning Scala I've wanted to try to replicate much of our functionality within a more minimal Scala stack (Squeryl, Scalatra, Scalate) to see if I can decrease code and improve performance (an Achilles heal for us right now).
Often my way of doing things is influenced by our previous stack, so I'm open to advice on a way of doing things that are closer to Scala paradigms. However, I've chosen some of what I do based on previous paradigms we have in the Java code base so that other team members will hopefully be more receptive to the work I'm doing. But here is my question:
We have a domain class like so:
class Person(var firstName: String, var lastName: String)
Within a jade template I make a call like:
.section
- view(fields)
The backing class has a list of fields like so:
class PersonBean(val person: Person) {
val fields: Fields = Fields(person,
List(
Text(person.firstName),
Text(person.lastName)
))
}
Fields has a base object (person) and a list of Field objects. Its template prints all its fields templates. Text extends Field and its Jade template is supposed to print:
<label for="person:firstName">#{label}</label>: <input type="text" id="person:firstName" value="#{value}" />
Now the #{value} is simply a call to person.firstName. However, to find out the label I reference a ResourceBundle and need to produce a string key. I was thinking of using a naming convention like:
person.firstName.field=First Name
So the problem then becomes, how can I within the Text class (or parent Field class) discover what the parameter being passed in is? Is there a way I can pass in person.firstName and find that it is calling firstName on class Person? And finally, am I going about this completely wrong?
If you want to take a walk on the wild side, there's a (hidden) API in Scala that allows you to grab the syntax tree for a thunk of code - at runtime.
This incantation goes something like:
scala.reflect.Code.lift(f).tree
This should contain all the information you need, and then some, but you'll have your work cut out interpreting the output.
You can also read a bit more on the subject here: Can I get AST from live scala code?
Be warned though... It's rightly classified as experimental, do this at your own risk!
You can never do this anywhere from within Java, so I'm not wholly clear as to how you are just following the idiom you are used to. The obvious reason that this is not possible is that Java is pass-by-value. So in:
public void foo(String s) { ... }
There is no sense that the parameter s is anything other than what it is. It is not person.firstName just because you called foo like:
foo(person.firstName);
Because person.firstName and s are completely separate references!
What you could do is replacing the fields (e.g. firstname) with actual objects, which have a name attribute.
I did something similiar in a recent blog post:http://blog.schauderhaft.de/2011/05/01/binding-scala-objects-to-swing-components/
The property doesn't have a name property (yet), but it is a full object but is still just as easy to use as a field.
I would not be very surprised if the following is complete nonsense:
Make the parameter type of type A that gets passed in not A but Context[A]
create an implicit that turns any A into a Context[A] and while doing so captures the value of the parameter in a call-by-name parameter
then use reflection to inspect the call-by-name parameter that gets passed in
For this to work, you'd need very specific knowledge of how stuff gets turned into call-by-name functions; and how to extract the information you want (if it's present at all).
Let's say I have the following class:
class Person(val firstName:String, val lastName:String)
Is there an automatic way to generate xml from this class without having to hand create a toXml() method? Ideally the output would be something like:
<Person>
<firstName>John</firstName>
<lastName>Smith</lastName>
</Person>
It seems like there should be a way to do this without having to write all that out manually. Perhaps there is a trait I haven't found yet?
For case classes (or other subclasses of Product), this was once very easy to write generically: the name can be retrieved with productPrefix, all values are iterable via productIterator and the names of the fields via productElementName.
Unfortunately, productElementName has only had a very short life: it was added in revision 20958 and removed in revision 21223, apparently because it added too much weight to case classes (there's also an open ticket for it).
Unfortunately, I don't think there is such a magic trait. You could use something like XStream to accomplish this. However, it doesn't seem print all Scala classes that pretty automatically, so you probably need to write your own converter. Someone else has already done so in the case of Lists, I guess for your example you might need something similar.