I'm chaining two scopes. I expect that the model will return with only rows that answer the constraints in BOTH scopes.
public function scopeHasImages() {
return $this->has('images');
}
public function scopeCompleted() {
return $this->where('status', 'complete');
}
and then I use
Subject::completed()->hasImages()->limit(100)->get()[0]->status;
unfortunately result is "pending"
just to make things clear, this works:
Subject::completed()->limit(100)->get()[0]->status;
result is "complete"
Change your Local Scopes to return a \Illuminate\Database\Eloquent\Builder instance:
public function scopeHasImages($query)
{
return $query->has('images');
}
public function scopeCompleted($query)
{
return $query->where('status', 'complete');
}
And then chaining the scopes will work:
Subject::completed()->hasImages()->limit(100)->get();
Related
I would like to add a cross cutting strategy, that converts certain return types of Spring #RestController methods to another response entity.
Given, that I have an interface
interface AsyncResult<T> {
public CompletableFuture<T> getResult();
}
I would like to write
#RequestMapping(...)
public AsyncResult getAsyncResult() { return ... }
and create the actual response in some kind of strategy, e.g.
public ResponseEntity convert(AsyncResult result) {
if(result.getResult().isDone()) {
return new ResponseEntity(result.get(), HttpStatus.OK);
} else {
// headers e.g. AsyncResult: true, Poll-Location: /result/result-id
return new ResponseEntity(HttpStatus.ACCEPT, headers);
}
}
I guess that this is possible by registering something similar to an #ExceptionHandler ?
It looks like that the answer is to implement a org.springframework.web.method.support.HandlerMethodReturnValueHandler
I'm currently trying to pass data from my data provider to the setUp()-method in PHPUnit.
Background: I am using PHPUnit for running frontend-tests in different browsers. The browser should be defined inside the data provider and needs to be known by the setUp()-method.
I understand, that a data provider initially is executed before the setUp()-method (as setUpBeforeClass()) is called. Therefore setUp()-data can not be passed to a data provider. But it should work the other way round, shouldn't it?
Does PHPUnit generate its own temporarily testclasses with data from the data provider "integrated"?
Of course: a workaround could be, to read the XML-file in the setUp()-method again. But that's the last option, I'd consider...
EDIT: Provided a small snippet:
part of dataProvider():
public function dataProvider()
{
$this->xmlCnf = $data['config'];
var_dump($this->xmlCnf); // array with config is exposed
// [...]
}
And the setUp()-method:
protected function setUp()
{
var_dump($this->xmlCnf); // NULL
//[...]
}
In case this is useful to anyone:
The following code should work:
public function dataProvider()
{
return [ [ /* dataset 1 */] , ... ]
}
protected setUp() {
parent::setUp();
$arguments = $this->getProvidedData();
// $arguments should match the provided arguments for this test case
}
/**
* #dataProvider dataProvider
*/
public function testCase(...$arguments) {
}
The getProvidedData method seems to have been available since PHPUnit 5.6 (which was either shortly before or after this question was originally asked)
we can make the xmlCnf to static
private static $xmlCnf;
public function provider(){
self::$xmlCnf = 'hello';
var_dump(self::$xmlCnf); //hello
return [...];
}
public function setUp() {
var_dump(self::$xmlCnf); //hello
parent::setUp();
}
I create an Observable from a long running operation + callback like this:
public Observable<API> login(){
return Observable.create(new Observable.OnSubscribe<API>() {
#Override
public void call(final Subscriber<? super API> subscriber) {
API.login(new SimpleLoginListener() {
#Override
public void onLoginSuccess(String token) {
subscriber.onNext(API.from(token));
subscriber.onCompleted();
}
#Override
public void onLoginFailed(String reason) {
subscriber.onNext(API.error());
subscriber.onCompleted();
}
});
}
})
}
A successfully logged-in api is the pre-condition for multiple other operations like api.getX(), api.getY() so I thought I could chain these operation with RxJava and flatMap like this (simplified): login().getX() or login().getY().
My biggest problem is now, that I don't have control over when login(callback) is executed. However I want to be able to reuse the login result for all calls.
This means: the wrapped login(callback) call should be executed only once. The result should then be used for all following calls.
It seems the result would be similar to a queue that aggregates subscribers and then shares the result of the first execution.
What is the best way to achieve this? Am I missing a simpler alternative?
I tried code from this question and experiemented with cache(), share(), publish(), refCount() etc. but the wrapped function is called 3x when I do this for all of the mentioned operators:
apiWrapper.getX();
apiWrapper.getX();
apiWrapper.getY();
Is there something like autoConnect(time window) that aggregates multiple successive subscribers?
Applying cache() should make sure login is only called once.
public Observable<API> login() {
return Observable.create(s -> {
API.login(new SimpleLoginListener() {
#Override
public void onLoginSuccess(String token) {
s.setProducer(new SingleProducer<>(s, API.from(token)));
}
#Override
public void onLoginFailed(String reason) {
s.setProducer(new SingleProducer<>(s, API.error()));
}
});
}).cache();
}
If, for some reason you want to "clear" the cache, you can do the following trick:
AtomicReference<Observable<API>> loginCache = new AtomicReference<>(login());
public Observable<API> cachedLogin() {
return Observable.defer(() -> loginCache.get());
}
public void clearLoginCache() {
loginCache.set(login());
}
Ok I think I found one major problem in my approach:
Observable.create() is a factory method so even if every single observable was working as intented, I created many of them. One way to avoid this mistake is to create a single instance:
if(instance==null){ instance = Observable.create(...) }
return instance
The extension methods:
Response.AsJson
Response.AsXml
works fine when calling it from the constractor like:
public class TweetModule : NancyModule
{
public TweetModule()
: base("/")
{
Post["/{action}.json/"] = parameters =>
{
return Reponse.Asjson(new {output:parameters.action}); // OK
}
}
}
But when I call it from a function like this:
public class TweetModule : NancyModule
{
public TweetModule()
: base("/")
{
Post["/{action}.{format}/"] = parameters =>
{
return GetResponse( parameters.action,parameters.format); // Error
}
}
public Response GetResponse(string action,string format)
{
if (format == "json")
return Response.AsJson(new {output:action}); // error
else
return Response.AsXml(new {output:action}); // error
}
}
I get this exception:
<>f__AnonymousType0`1[System.String] cannot be serialized because it
does not have a parameterless constructor.
any advice?
Na that works just fine. The problem is that your captured parameter is called {fortmat} and you then pass along parameters.format which is never captured due to the typo
And I have to point out that your code won't even compile since function is not a valid keyword in C#, I just assumed that you actual meant it to say public instead.
Hope this helps
I need to override the call method from NetConnection class, the signature of the method is:
public function call(command:String, responder:Responder, ...parameters):void
How do I override that method?
The following lines didn't work for me.
override public function call(command:String, responder:Responder, ...parameters):void
{
super.call (command, responder, ...parameters);
}
override public function call(command:String, responder:Responder, ...parameters):void
{
super.call (command, responder, parameters);
}
Any clue?
Thanks in advance
parameters is an optional array, so you need to check if they exist.
if(parameters.length > 0) {
super.call(command, responder, parameters);
}
else {
super.call(command, responder);
}