So I'm using the JodaTime plugin in a grails project I'm implementing and I really don't like that it spits out the ISO8601 date format when I do a toString. I've been constantly putting toString and passing in the default.date.format from the messages file, but that's cumbersome. The majority of cases I just want it to do that automatically. So naturally it makes sense to take advantage of Groovy's fabulous metaprogramming to override toString on the DateTime class. But alas it doesn't work. Hence this discussion:
http://jira.codehaus.org/browse/GROOVY-4210
So according to said discussion, if our class implements an interface to implement the toString method we need to override the interface's metaclass. Looking at the joda code base, DateTime implements the ReadableDateTime interface which in turn inherits from ReadableInstant which is where the method signature is defined. The actual implementation is done 4 classes up in the class hierarchy for DateTime (DateTime inherits from BaseDateTime inherits from AbstractDateTime inherits from AbstractInstant which implements toString without parameters). With me so far?
So in theory this means I should override either the ReadableDateTime interface which doesn't actually have the toString signature or the ReadableInstant one which does. The following code to override toString on ReadableDateTime does nothing.
ReadableDateTime.metaClass.toString = { ->
delegate.toString(messageSource.getMessage(
'default.date.format', null, LCH.getLocale()))
}
So then trying with ReadableInstant:
ReadableInstant.metaClass.toString = { ->
delegate.toString(messageSource.getMessage(
'default.date.format', null, LCH.getLocale()))
}
also does not have the desired result for the DateTime.toString method. However, there are some interesting affects here. Take a look at the following code:
def aiToString = AbstractInstant.metaClass.getMetaMethod("toString", [] as Class[])
def adtToString = AbstractDateTime.metaClass.getMetaMethod("toString", [] as Class[])
def bdtToString = BaseDateTime.metaClass.getMetaMethod("toString", [] as Class[])
def dtToString = DateTime.metaClass.getMetaMethod("toString", [] as Class[])
def date = new DateTime()
println "ai: ${aiToString.invoke(date)} "
println "adt: ${adtToString.invoke(date)} "
println "bdt: ${bdtToString.invoke(date)} "
println "dt: ${dtToString.invoke(date)} "
The first 3 methods show my date formatted just how I'd like it. The last one is still showing the ISO8601 formatted date. I thought maybe the JodaTime plugin for grails might be overriding the toString and they do add a few methods to these interfaces but nothing to do with toString. At this point, I'm at a loss. Anyone have ideas?
Thanks
You cann't override DateTime#toString(), becouse DateTime class is final
public final class DateTime
But if you want another date format, you can use toString(org.joda.time.format.DateTimeFormatter)
for example
def date = new DateTime();
date.toString(ISODateTimeFormat.basicDate()); // format yyyyMMdd
Related
i am new in grails 3 and i wanted to know that how we can get the values from the database to the controller
i tried
def std = Students.get(1)
but it returns only the id not the actual value
plzzzz can anyone help me
You could also do:
def std = Students.findById(id);
If you are printing the result of get, the toString() default methods is call if you haven't create your own. Then if you do:
def std = Students.get(1)
println std
Students: 1 will be printed
You can implement your toString() method as:
Students{
String name
String toString(){
name
}
}
In this case the result of println will be its name.
If you want to print all fields of the object just do
println std.dump()
I have a pipeline that successfully outputs an Avro file as follows:
#DefaultCoder(AvroCoder.class)
class MyOutput_T_S {
T foo;
S bar;
Boolean baz;
public MyOutput_T_S() {}
}
#DefaultCoder(AvroCoder.class)
class T {
String id;
public T() {}
}
#DefaultCoder(AvroCoder.class)
class S {
String id;
public S() {}
}
...
PCollection<MyOutput_T_S> output = input.apply(myTransform);
output.apply(AvroIO.Write.to("/out").withSchema(MyOutput_T_S.class));
How can I reproduce this exact behavior except with a parameterized output MyOutput<T, S> (where T and S are both Avro code-able using reflection).
The main issue is that Avro reflection doesn't work for parameterized types. So based on these responses:
Setting Custom Coders & Handling Parameterized types
Using Avrocoder for Custom Types with Generics
1) I think I need to write a custom CoderFactory but, I am having difficulty figuring out exactly how this works (I'm having trouble finding examples). Oddly enough, a completely naive coder factory appears to let me run the pipeline and inspect proper output using DataflowAssert:
cr.RegisterCoder(MyOutput.class, new CoderFactory() {
#Override
public Coder<?> create(List<? excents Coder<?>> componentCoders) {
Schema schema = new Schema.Parser().parse("{\"type\":\"record\,"
+ "\"name\":\"MyOutput\","
+ "\"namespace\":\"mypackage"\","
+ "\"fields\":[]}"
return AvroCoder.of(MyOutput.class, schema);
}
#Override
public List<Object> getInstanceComponents(Object value) {
MyOutput<Object, Object> myOutput = (MyOutput<Object, Object>) value;
List components = new ArrayList();
return components;
}
While I can successfully assert against the output now, I expect this will not cut it for writing to a file. I haven't figured out how I'm supposed to use the provided componentCoders to generate the correct schema and if I try to just shove the schema of T or S into fields I get:
java.lang.IllegalArgumentException: Unable to get field id from class null
2) Assuming I figure out how to encode MyOutput. What do I pass to AvroIO.Write.withSchema? If I pass either MyOutput.class or the schema I get type mismatch errors.
I think there are two questions (correct me if I am wrong):
How do I enable the coder registry to provide coders for various parameterizations of MyOutput<T, S>?
How do I values of MyOutput<T, S> to a file using AvroIO.Write.
The first question is to be solved by registering a CoderFactory as in the linked question you found.
Your naive coder is probably allowing you to run the pipeline without issues because serialization is being optimized away. Certainly an Avro schema with no fields will result in those fields being dropped in a serialization+deserialization round trip.
But assuming you fill in the schema with the fields, your approach to CoderFactory#create looks right. I don't know the exact cause of the message java.lang.IllegalArgumentException: Unable to get field id from class null, but the call to AvroCoder.of(MyOutput.class, schema) should work, for an appropriately assembled schema. If there is an issue with this, more details (such as the rest of the stack track) would be helpful.
However, your override of CoderFactory#getInstanceComponents should return a list of values, one per type parameter of MyOutput. Like so:
#Override
public List<Object> getInstanceComponents(Object value) {
MyOutput<Object, Object> myOutput = (MyOutput<Object, Object>) value;
return ImmutableList.of(myOutput.foo, myOutput.bar);
}
The second question can be answered using some of the same support code as the first, but otherwise is independent. AvroIO.Write.withSchema always explicitly uses the provided schema. It does use AvroCoder under the hood, but this is actually an implementation detail. Providing a compatible schema is all that is necessary - such a schema will have to be composed for each value of T and S for which you want to output MyOutput<T, S>.
Ruby setters—whether created by (c)attr_accessor or manually—seem to be the only methods that need self. qualification when accessed within the class itself. This seems to put Ruby alone the world of languages:
All methods need self/this (like Perl, and I think Javascript)
No methods require self/this is (C#, Java)
Only setters need self/this (Ruby?)
The best comparison is C# vs Ruby, because both languages support accessor methods which work syntactically just like class instance variables: foo.x = y, y = foo.x . C# calls them properties.
Here's a simple example; the same program in Ruby then C#:
class A
def qwerty; #q; end # manual getter
def qwerty=(value); #q = value; end # manual setter, but attr_accessor is same
def asdf; self.qwerty = 4; end # "self." is necessary in ruby?
def xxx; asdf; end # we can invoke nonsetters w/o "self."
def dump; puts "qwerty = #{qwerty}"; end
end
a = A.new
a.xxx
a.dump
take away the self.qwerty =() and it fails (Ruby 1.8.6 on Linux & OS X). Now C#:
using System;
public class A {
public A() {}
int q;
public int qwerty {
get { return q; }
set { q = value; }
}
public void asdf() { qwerty = 4; } // C# setters work w/o "this."
public void xxx() { asdf(); } // are just like other methods
public void dump() { Console.WriteLine("qwerty = {0}", qwerty); }
}
public class Test {
public static void Main() {
A a = new A();
a.xxx();
a.dump();
}
}
Question: Is this true? Are there other occasions besides setters where self is necessary? I.e., are there other occasions where a Ruby method cannot be invoked without self?
There are certainly lots of cases where self becomes necessary. This is not unique to Ruby, just to be clear:
using System;
public class A {
public A() {}
public int test { get { return 4; }}
public int useVariable() {
int test = 5;
return test;
}
public int useMethod() {
int test = 5;
return this.test;
}
}
public class Test {
public static void Main() {
A a = new A();
Console.WriteLine("{0}", a.useVariable()); // prints 5
Console.WriteLine("{0}", a.useMethod()); // prints 4
}
}
Same ambiguity is resolved in same way. But while subtle I'm asking about the case where
A method has been defined, and
No local variable has been defined, and
we encounter
qwerty = 4
which is ambiguous—is this a method invocation or an new local variable assignment?
#Mike Stone
Hi! I understand and appreciate the points you've made and your
example was great. Believe me when I say, if I had enough reputation,
I'd vote up your response. Yet we still disagree:
on a matter of semantics, and
on a central point of fact
First I claim, not without irony, we're having a semantic debate about the
meaning of 'ambiguity'.
When it comes to parsing and programming language semantics (the subject
of this question), surely you would admit a broad spectrum of the notion
'ambiguity'. Let's just adopt some random notation:
ambiguous: lexical ambiguity (lex must 'look ahead')
Ambiguous: grammatical ambiguity (yacc must defer to parse-tree analysis)
AMBIGUOUS: ambiguity knowing everything at the moment of execution
(and there's junk between 2-3 too). All these categories are resolved by
gathering more contextual info, looking more and more globally. So when you
say,
"qwerty = 4" is UNAMBIGUOUS in C#
when there is no variable defined...
I couldn't agree more. But by the same token, I'm saying
"qwerty = 4" is un-Ambiguous in ruby
(as it now exists)
"qwerty = 4" is Ambiguous in C#
And we're not yet contradicting each other. Finally, here's where we really
disagree: Either ruby could or could not be implemented without any further
language constructs such that,
For "qwerty = 4," ruby UNAMBIGUOUSLY
invokes an existing setter if there
is no local variable defined
You say no. I say yes; another ruby could exist which behaves exactly like
the current in every respect, except "qwerty = 4" defines a new
variable when no setter and no local exists, it invokes the setter if one
exists, and it assigns to the local if one exists. I fully accept that I
could be wrong. In fact, a reason why I might be wrong would be interesting.
Let me explain.
Imagine you are writing a new OO language with accessor methods looking
like instances vars (like ruby & C#). You'd probably start with
conceptual grammars something like:
var = expr // assignment
method = expr // setter method invocation
But the parser-compiler (not even the runtime) will puke, because even after
all the input is grokked there's no way to know which grammar is pertinent.
You're faced which a classic choice. I can't be sure of the details, but
basically ruby does this:
var = expr // assignment (new or existing)
// method = expr, disallow setter method invocation without .
that is why it's un-Ambiguous, while and C# does this:
symbol = expr // push 'symbol=' onto parse tree and decide later
// if local variable is def'd somewhere in scope: assignment
// else if a setter is def'd in scope: invocation
For C#, 'later' is still at compile time.
I'm sure ruby could do the same, but 'later' would have to be at runtime, because
as ben points out you don't know until the statement is executed which case
applies.
My question was never intended to mean "do I really need the 'self.'?" or "what
potential ambiguity is being avoided?" Rather I wanted to know why was this
particular choice made? Maybe it's not performance. Maybe it just got the job
done, or it was considered best to always allow a 1-liner local to override a
method (a pretty rare case requirement) ...
But I'm sort of suggesting that the most dynamical language might be the one which
postpones this decision the longest, and chooses semantics based on the most contextual
info: so if you have no local and you defined a setter, it would use the setter. Isn't
this why we like ruby, smalltalk, objc, because method invocation is decided at runtime,
offering maximum expressiveness?
Well, I think the reason this is the case is because qwerty = 4 is ambiguous—are you defining a new variable called qwerty or calling the setter? Ruby resolves this ambiguity by saying it will create a new variable, thus the self. is required.
Here is another case where you need self.:
class A
def test
4
end
def use_variable
test = 5
test
end
def use_method
test = 5
self.test
end
end
a = A.new
a.use_variable # returns 5
a.use_method # returns 4
As you can see, the access to test is ambiguous, so the self. is required.
Also, this is why the C# example is actually not a good comparison, because you define variables in a way that is unambiguous from using the setter. If you had defined a variable in C# that was the same name as the accessor, you would need to qualify calls to the accessor with this., just like the Ruby case.
The important thing to remember here is that Ruby methods can be (un)defined at any point, so to intelligently resolve the ambiguity, every assignment would need to run code to check whether there is a method with the assigned-to name at the time of assignment.
Because otherwise it would be impossible to set local variables at all inside of methods. variable = some_value is ambiguous. For example:
class ExampleClass
attr_reader :last_set
def method_missing(name, *args)
if name.to_s =~ /=$/
#last_set = args.first
else
super
end
end
def some_method
some_variable = 5 # Set a local variable? Or call method_missing?
puts some_variable
end
end
If self wasn't required for setters, some_method would raise NameError: undefined local variable or method 'some_variable'. As-is though, the method works as intended:
example = ExampleClass.new
example.blah = 'Some text'
example.last_set #=> "Some text"
example.some_method # prints "5"
example.last_set #=> "Some text"
I have just take a look at the 3º tutorial from dart, creating the rating component. I was wondering if there is same method which is called when stringifying an object, something similar to Java's toString.
For example:
MyClass myObject = new MyClass();
System.out.println(myObject);
Will call MyClass.toString() if overwriten, else will call it's parent until java.lang.Object is reached giving a default toString.
I find kind ugly (completely subjective) doing:
<span ng-repeat="star in cmp.stars" > {{star.toString()}} </span>
I would rather do:
<span ng-repeat="star in cmp.stars" > {{star}} </span>
And give the implementation of how I want it to display at an averwritten method. Is this possible?
If you have something like this:
class MyClass {
String data;
MyClass(this.data);
#override
String toString() {
return data;
}
}
MyClass myObject = new MyClass("someData");
print(myObject); // outputs "someData", not 'Instance of MyClass'
I think this might be what you are looking for.
Yes it works like this for print, String interpolation or Angular mustaches.
By overriding the String toString() method on your object the displayed value will be the result of this toString() call. If there's no toString() defined in the class hierarchy the toString() of Object will be called (which will return Instance of 'MyClass' for class MyClass{}).
You may be interesting look how Rating component was implemented in Angular Dart UI project. Check this out.
Sergey.
i am trying to get a situation where i can use i18n property files which are backed up with a database?
So for some standard stuff i would like to use the property files, but some fields must be editable by the end-user so i was planning to use i18n in the database for that. So a real combination would be great. If the i18n code cannot be found in the property files then do a lookup in the DB.
Any idea how i can tackle this? I have seen the post Grails i18n From Database but Default Back To File
But there is no real answer to the problem, any other suggestions on how to tackle this?
Put a new domain class into your project:
class Message {
String code
Locale locale
String text
}
Add the following lines to your resources.groovy:
// Place your Spring DSL code here
beans = {
messageSource(DatabaseMessageSource) {
messageBundleMessageSource = ref("messageBundleMessageSource")
}
messageBundleMessageSource(org.codehaus.groovy.grails.context.support.PluginAwareResourceBundleMessageSource) {
basenames = "WEB-INF/grails-app/i18n/messages"
}
}
And add the following class to your src/groovy folder:
class DatabaseMessageSource extends AbstractMessageSource {
def messageBundleMessageSource
protected MessageFormat resolveCode(String code, Locale locale) {
Message msg = messageBundleMessageSource.resolveCode(code, locale)
def format
if(msg) {
format = new MessageFormat(msg.text, msg.locale)
}
else {
format = Message.findByCodeAndLocale(code, locale)
}
return format;
}
}
Now grails will try to resolve the message from the message bundle. If it is not available, it will look it up from database. You could add some error-handling, but this version works, if all messages are available at least in one place.
See http://graemerocher.blogspot.com/2010/04/reading-i18n-messages-from-database.html for some more details.
Some details on the changes done in resources.groovy:
In this file you can define injectable groovy classes, which can be included by just defining a variable having the same name as defined in the resources.groovy. E.g. in this file, there are messageSource and messageBundleMessageSource, which you can be include in any controller or service files. If this variable is defined, an instance of the class in the brackets is created.
In this case, we overwrite the general messageSource to use our custom implementation DatabaseMessageSource. So the I18n function message will now use our custom implementation.
Since our custom implementation requires to check the message.properties-files we keep the original message source in the second bean. By defining this instance in our custom implementation, we can still use the old implementation (and therefore looking up messages the usual way).
I'm not sure I know what you mean by
i18n property files which are backed up with a database
But if you simply mean that you want the message keys to be resolved using a database table (instead of a .properties file), then you can do this by writing your own implementation of the MessageSource interface
class DBMessageSource implements MessageSource {
String getMessage(MessageSourceResolvable resolvable, Locale locale) {
// IMPLEMENT ME
}
String getMessage(String code, Object[] args, Locale locale) {
// IMPLEMENT ME
}
String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
// IMPLEMENT ME
}
}
Then simply replace the default implementation of the messageSource bean with your implementation by adding the following to resources.groovy
messageSource(DBMessageSource)
In followup of the answer of #crudolf i implemented the following method to achieve my goal.
class DatabaseMessageSource extends AbstractMessageSource {
// the message bundle resource that holds all of the messages
def messageBundleMessageSource
// the default locale used when there is no correct results found
// if a visitor (x) comes along with an unknown locale in the DB
// then this locale will be used as fallback!
Locale fallbackLocale = new Locale("nl", "NL")
protected MessageFormat resolveCode(String code, Locale locale) {
// first try to find the message in the messagebundles
MessageFormat messageFormat = messageBundleMessageSource.resolveCode(code, locale)
if(!messageFormat) {
// no message found so lets find one in the database
def message = Message.findByCodeAndLocale(code, locale) ?: Message.findByCodeAndLocale(code, fallbackLocale)
if (message) {
// found one create a message format!
messageFormat = new MessageFormat(message.text, message.locale)
} else {
// not found! create a standard message format
messageFormat = new MessageFormat(code, locale)
}
}
return messageFormat
}
}
Take a look at https://github.com/goeh/grails-i18n-db and https://github.com/halfbaked/grails-localizations. Both offer also a gui to manage localizations.