4. it will say winenr no matter what, but the color of the winner text will simblize who won. all the dots will also turn that color.
.
4. it will say winenr no matter what, but the color of the winner text will simblize who won. all the dots will also turn that color.
.
The majority of self-help material is little more than inconsequential banal garbage that provides light titillation to its gullible consumers. The Secret, however, is far more insidious. The implicit messages are actually quite reckless and extremely inappropriate. At one point, one of the 'experts' claims that being involved in a car crash is merely a result of your thought patterns and it could have been avoided with more positive thinking. Seriously, he actually said that. How does an incest survivor process this kind of information? Given the type of vulnerable people that will be drawn to a documentary like this, it is actually pretty disgusting to hear such idiotic comments.
.
At times it is actually quite hard to discern whether this is just satire, but sadly it is not.
.
One of the single worst pieces of television ever made. Every piece of human garbage associated with this repulsive bilge deserves to be publicly shamed.
.
Gutentag::ActiveRecord.call self
first time I've seen this API in Ruby
Most would just do include Gutentag::ActiveRecord. or acts_as_taggable
You could also check if Time.now > @user.last_active+10.minutes before updating to make sure that you aren't constantly writing to the db
efficiency compromise
or the endangerment of public health
unless preventing people from freely discussing/sharing about what information/treatments they believe is effective/helpful for public health ... is actually more harmful to public health than allowing them to freely post.
ARRAY( SELECT DISTINCT ... FROM unnest(arr) )
And that can all can be written with CROSS JOIN LATERAL which is much cleaner, SELECT ARRAY( SELECT DISTINCT e FROM ( VALUES ('foo', 'bar', 'foo', 'baz' ) ) AS t(a,b,c,d) CROSS JOIN LATERAL unnest(ARRAY[a,b,c,d]) AS a(e) -- ORDER BY e; -- if you want it sorted );
share.riseup.net — file upload (pastebin and imagebin).
There are two pairs of methods for sending/receiving messages: Object#send and ::receive for when the sender knows the receiver (push); Ractor.yield and Ractor#take for when the receiver knows the sender (pull);
When i started using body wash I hit the jackpot. I use a 3 to 1 ratio of water to body wash and get fantastic results with an occasional clog
.
it kinda works, but obviously, never as good as the original foaming soap. The reason for that is, the foaming soap has a slightly different formula than regular soap. Specifically, it has more foaming ingredients (like sodium lauryl sulfate / sodium laureth sulfate) and less actual "soap".
.
The sad part of it all is that the manufacturers have found yet another way to rip off the consumer. They put one fourth the amount of soap in three fourths H20, change the dispenser slightly and then charge 4 times as much for the finished product. You do the math,
.
Hence an email address/mailbox/addr-spec is "local-part@domain"; "local-part" is composed of one or more of 'word' and periods; "word" can be an "atom" which can include anything except "specials", control characters or blank/space; and specials (the *only* printable ASCII characters [other than space, if you call space "printable"] *excluded* from being a valid "local-part") are: ()<>@,;:\".[] Therefore by the official standard for email on the internet, the plus sign is as much a legal character in the local-part of an email address as "a" or "_" or "-" or most any other symbol you see on the main part of a standard keyboard.
There's a common design flaw on many many websites that require an email address to register; most recently I came across this bug on CNet's download.com site: for some reason they don't accept me when I try to register an email address containing a "+", and they then send me back saying my address is invalid. It isn't!
"+" is a completely valid character in an email address; as defined by the internet messaging standard published in 1982(!) RFC 822 (page 8 & 9)... Any website claiming anything else is wrong by definition, plus they are prohibiting me and many fellow anti-spam activists from tracking where inbound spam comes from:
Screening is a useful way of avoiding spam and/or other unwanted correspondence.
Filing is the simplest application to take advantage of plus signs.
The "+tag" portion of the email address can then be used both for filing mail and for screening it.
The current behaviour is definitely broken (at least in my mind). I don't think I'd consider it a feature just because it's been around a while.
Given that 5.2 and 6.0 now have this current (broken?) behavior, I wonder if this behavior will now be considered as breaking change.
we often work hard to make symbols and strings interchangeable in contexts where it makes sense
lateral (select pledged / fx_rate as pledged_usd) pu, lateral (select pledged_usd / backers_count as avg_pledge_usd) apu, lateral (select goal / fx_rate as goal_usd) gu, lateral (select goal_usd - pledged_usd as usd_from_goal) ufg, lateral (select (deadline - launched_at)/86400.00 as duration) dr
Comment[:article_id].in(Arel.sql(articles_sql))
Query values including NULLs Because .where.not can be counter-intuitive regarding NULL values, you can use is_distinct_from to include them. User.where(User[:active].is_distinct_from(true))
User.order(User[:email].desc.nulls_last)
User.order( Arel::Nodes::Case .new(User[:role]) .when("admin").then(1) .when("editor").then(2) )
User.distinct.pluck(User[:created_at].extract("year"))
space = Arel.sql("' '") User.pluck(User[:first_name].concat(space).concat(User[:last_name]))
User.where(User[:email].matches("%@example.org")) # => SELECT "users".* FROM "users" WHERE "users"."email" ILIKE '%@example.org'
User.where(User[:email].lower.eq(email.downcase)) # => SELECT "users".* FROM "users" WHERE LOWER("users"."email") = 'user@example.org'
class ApplicationRecord < ActiveRecord::Base def self.[](attribute) arel_table[attribute] end end
It's safe to use CROSS JOIN LATERAL (or just , LATERAL) here, because the array constructor always returns a row. Else, if a lateral subquery could come up empty (no row), you would use LEFT JOIN LATERAL (...) ON true to avoid losing rows.
.
Although COALESCE, GREATEST, and LEAST are syntactically similar to functions, they are not ordinary functions
You can use to_char to convert the timestamp using appropriate format mask: COALESCE(to_char(timestamp_type, 'YYYY-MM-DD'), varchar_col)
But it's MUCH better to not rely on datestyle settings for converting date-times to/from text.
StopTheMadness is a web browser extension that stops web sites from making your browser harder to use
"The good news is that you can wrest control of your browser back from these malicious, control-freak sites."
unfortunately only iOS and Mac
see instead: - https://addons.mozilla.org/en-US/firefox/addon/enable-selection/?utm_source=addons.mozilla.org&utm_medium=referral&utm_content=search
Dispatch a custom event. This differs from Svelte's component event system, because these events require a DOM element as a target, can bubble (and do by default), and are cancelable with event.preventDefault(). All SMUI events are dispatched with this instead of Svelte's createEventDispatcher.
In addition, a component that uses Svelte's built in event forwarding system cannot allow event listeners on the "capture" phase of the event lifecycle. It also cannot allow events to be cancelable with the browser's built in preventDefault function.
This is especially useful for UI library components, as it is generally unknown which events will be required from them for all desired use cases. For example, if a Button component only forwards a click event, then no use case that requires the mouseover or the keypress event can be used with it.
This thing has struck a nerve here. Literally overnight millions of people are talking about real things again. But in such an abrupt way, it's odd, like they were suddenly turned on after having been flash frozen for the last two years.
.
I want to filter emails to exclude starred message threads. Even a simple "-is:starred" or "-has:yellow-star" does not work.
limitation
dmsetup remove /dev/dm-5
.
udisksctl unlock -b /dev/sdg1
.
class Note < ApplicationRecord delegated_type :authorable, types: %w[ Customer Employee ] end
Checkout this PR to know more about this feature.
typo
The existence of polymorphic associations does not allow the database to enforce referential integrity, however, because no foreign keys can be defined.
Good point. In my example, cardinalities would be fundamentally different: an Entry could have_many :messages and have_many :comments. In the original example, a Message could have_many :entries, etc. In either case, there's no way to enforce the cardinalities at the database level (not that I'm aware of).
@entry = Entry.create! entryable: Spot.new(params.require(:spot).permit(:address)) redirect_to @entry # Redirects to e.g. /spots/47, with 47 being the newly created Entry id.
Delegated types newly introduced here looks like a Class Table Inheritance (CTI).
I did a spike to come up with a PoC for introducing this into the codebase of a product that I'm working on (matteeyah/respondo#225) by monkey-patching ActiveRecord with delegated types. It's amazing how can a small code change in ActiveRecord facilitate a big change in the domain model.
I just thought that if there was any time to improve the naming it would be now, before rolling it out to thousands of devs/projects. I don't think of that as bikeshedding, personally.
I think I might inadvertently have shared plans for a bike shed and opened the floor to which color it should be painted. My sincerest apologies
That was my initial reaction too. I think because we are used to talking about delegating behavior, whereas this is delegating subtyping. Or in other words, delegating the ability to be extended with specialized behavior.
we're used to "delegating" meaning...
Is the name "delegated type" up for review? I don't see any delegation happening in the code. It looks more like a "subtype", or "secondary type", or something like that.
From the text as it is currently written, though, it is not entirely clear what the advantage would be of this new technique vs. using plain composition.
That's not clear to me either
A very visible aspect of the object-relational mismatch is the fact that relational databases don't support inheritance. You want database structures that map clearly to the objects and allow links anywhere in the inheritance structure. Class Table Inheritance supports this by using one database table per class in the inheritance structure.
Another strategy is reinforcement learning (aka. constraint learning), as used in some AI systems.
has the operator return its first defined argument, then pass over the next defined one in case of a dead-end, in a depth-first selection algorithm.
The evaluation may result in the discovery of dead ends, in which case it must "switch" to a previous branching point and start over with a different alternative.
They allow for writing nondeterministic programs which contain various alternatives for the program flow.
Ambiguous functions
You may want to jump straight to the Examples section if formal stuff annoys you.
formal stuff annoys you
prefer practical vs. prefer theoretical/academic
A continuation is like a savepoint, representing "what's left to run" at a given time.
I tested it, and it indeed works, but I don't want to depend on a to-be-removed feature.
I am using them in a real life application. I am calculating the available tables for a full calendar with many time slots and with respect to many configurable business rules for restaurants. Using callcc this feature got blazingly fast and very nicely readable. Also we use it to optimise table arrangements with respect to complex restaurant business rules (even something like: Guest A doesn't like to sit near Guest B). Please just have a look at these resources: https://github.com/chikamichi/amb/tree/master/examples http://web.archive.org/web/20151116124853/http://liufengyun.chaos-lab.com/prog/2013/10/23/continuation-in-ruby.html Please help me to keep Guest A away from Guest B. Bad things might happen.
"Context" manipulation is one of big topic and there are many related terminologies (academic, language/implementation specific, promotion terminologies). In fact, there is confusing. In few minutes I remember the following related words and it is good CS exam to describe each :p Thread (Ruby) Green thread (CS terminology) Native thread (CS terminology) Non-preemptive thread (CS terminology) Preemptive thread (CS terminology) Fiber (Ruby/using resume/yield) Fiber (Ruby/using transfer) Fiber (Win32API) Generator (Python/JavaScript) Generator (Ruby) Continuation (CS terminology/Ruby, Scheme, ...) Partial continuation (CS terminology/ functional lang.) Exception handling (many languages) Coroutine (CS terminology/ALGOL) Semi-coroutine (CS terminology) Process (Unix/Ruby) Process (Erlang/Elixir) setjmp/longjmp (C) makecontext/swapcontext (POSIX) Task (...)
Using callcc this feature got blazingly fast and very nicely readable.
This (somewhat contrived) example allows the inner loop to abandon processing early: callcc {|cont|   for i in 0..4     print "\n#{i}: "     for j in i*5...(i+1)*5       cont.call() if j == 17       printf "%3d", j     end   end }
For example, did you known React has nothing to do with reactive programming?
Ruby should not completely ignore blocks. const_set :Example, Class.new do p "Hello, world" end # Doesn't print anything, generate any warning nor error. To minimize any impact, Ruby should issue a warning, and in future version could even raise an error. Even unused variables provide warnings in verbose mode, and they have their use. I can't think of a case where passing a block to a builtin method that doesn't accept a block is not a programming error though.
But since it can't be fixed generally, then just add a check in each core method that doesn't accept block, update its def to include a check.
Where I've been bitten by this was some Enumerable method that I assumed took a block. I think it was first { cond }, and I assumed it worked the same as detect { cond }
The remaining problem should be how to declare Ruby-define methods to be 'non-block taking'. Under the current language spec, absence of '& argument' may or may not mean the method would take a block.
This solution can hide a bad user experience. We’re not making any DOM changes on AJAX success, meaning Capybara can’t automatically detect when the AJAX completes. If Capybara can’t see it, neither can our users. Depending on your application, this might be OK.
.
As of Rails 7.0+, Active Record has an option for handling associations that would perform a join across multiple databases.
impressive
You can also use silence_redefinition_of_method if you need to define the replacement method yourself (because you're using delegate, for example).
You need to balance several factors: the need for new features, the increasing difficulty of finding support for old code, and your available time and skills, to name a few.
I am open to discussion but I don't want to jump on the conclusion.
The biggest reason is that we still have several options, so I didn't want to restrict the future possibility.
Shouldn't the #descendants method be the reverse of #ancestors?
personally, i think this is useful when you have objects which are not stored in database, as shown in the database, e.g. temperature, gps location, balance, etc. You might ask then why those are not stored in the database? In the database we only store a value, but if we want to attach useful, relevant methods to that value,
composed_of attr, :class_name => 'AddressableRecord::Address', :converter => :convert, :allow_nil => true,
In computer science, a value object is a small object that represents a simple entity whose equality is not based on identity: i.e. two value objects are equal when they have the same value, not necessarily being the same object.
There is nothing stopping you from creating store objects which scrapes XE for the current rates or just returns rand(2):
For example the german city munich in german München .. both save a city-model with a name translated all app-locales.
doesn't seem all that useful if that's all it does
most place names would be the same in any language
belongs_to :city
belongs_to :zipcode
Country State (belongs to country) City (belongs to State) Neighborhood (belongs to city)
Address (Belongs to Neighborhood and City, because neighborhood is not required)
biggs is a small ruby gem/rails plugin for formatting postal addresses from over 60 countries.
By default the wizard will render a view with the same name as the step. So for our controller AfterSignupController with a view path of /views/after_signup/ if call the :confirm_password step, our wizard will render /views/after_signup/confirm_password.html.erb
To send someone to the first step in this wizard we can direct them to after_signup_path(:confirm_password)
steps :confirm_password, :confirm_profile, :find_friends
Note that render_wizard does attempt to save the passed object. This means that in the above example, the object will be saved twice. This will cause any callbacks to run twice also. If this is undesirable for your use case, then calling assign_attributes (which does not save the object) instead of update might work better.
acceptable
Notice: Another method for partial validations, which might be considered more flexible by some users (allowing for easy validation testing inside model tests), was described by Josh McArthur here.
I liked the linked-to solution
The best way to build an object incrementally with validations is to save the state of our product in the database and use conditional validation. To do this we're going to add a status field to our Product class.
.
people want to have an object, lets call it a Product that they want to create in several different steps
This action will work a little differently from a normal create action that you might be used to, as it doesn’t strictly need a new action - we won’t be saving this Pet model with any data - just putting it in the database so that our StepsController can access that.
Remember, our wizard controller is responsible for showing and updating steps, but our top-level controller is still responsible for managing our Pet models.
and calls .unarchived and .archived appropriately when passed an ActiveRecord relation.
acts_as_tokened Quickly adds rails 5 has_secure_token to your model, along with some Post.find() enhancements to work with tokens instead of IDs.
include Effective::CrudController
# All queries and objects will be built with this scope resource_scope -> { current_user.posts } # Similar to above, with block syntax resource_scope do Post.active.where(user: current_user) end
Loads an appropriate @posts or @post type instance variable.
Replaces your Rails controllers, views and forms with meta programming. Considers routes.rb, ability.rb, current_user and does the right thing.
The goal of this gem is to reduce the amount of code that needs to be written when developing a ruby on rails website.
enumerate_by :alpha_2_code
Note that this is a reference implementation and, most likely, should be modified for your own usage.
[:state, :zip]
presumably this groups them together more indivisibly, perhaps so they'll show up as a single line, for example?
alias_method :normalize_whitespace_with_warning, :normalize_whitespace def normalize_whitespace(*args) silence_warnings do normalize_whitespace_with_warning(*args) end end
suppress warnings
Since factory_bot_rails automatically loads factory definitions as your application loads, writing a definition like this would cause another Daniel to get added to your database every time you start the server or open a console. I like Daniels and all, but there is a limit.
As a workaround, you can use setters in every affected reactive block instead of direct assignment. let localForm = {}; const setLocalForm = (data) => { localForm = data; }; $: setLocalForm({...$formData});
Even though not all code smells indicate real problems (think fluent interfaces)
At this point I would call into question the job of Event to both be responsible for managing what gets charged and how something should be charged. I would probably investigate moving those to external service classes to keep charging responsibilities out of a simple event object.
however, I prefer to take it as an indication that a pretty smart group of people didn't think there was a particularly strong reason to use a different term.
seems reasonable
Unfortunately, I think a lot of the answers here are perpetuating or advancing the idea that there's some complex, meaningful difference. Really - there isn't all that much to it, just different words for the same thing.
'method' is the object-oriented word for 'function'. That's pretty much all there is to it (ie., no real difference).
a function is a mathematical construct. I would say all methods are functions but not all functions are methods
theory
Coming from a functional programming background, I feel there is a profound distinction between function and method. Mainly methods have side effects, and that functions should be pure thus giving a rather nice property of referential transparency
I agree it might be nice if "function" and "method" meant what you wanted them to, but your definitions do not reflect some very common uses of those terms.
Unfortunately, if the number of command-line arguments argc is 0 – which means if the argument list argv that we pass to execve() is empty, i.e. {NULL} – then argv[0] is NULL. This is the argument list’s terminator.
subtle bug
Ruby 2.6 introduces an initial implementation of a JIT (Just-In-Time) compiler. The JIT compiler aims to improve the performance of Ruby programs. Unlike traditional JIT compilers which operate in-process, Ruby’s JIT compiler writes out C code to disk and spawns a common C compiler to generate native code. For more details about it, see the MJIT organization by Vladimir Makarov.
For example, if you pre-build a swordman, a spearman and an horseman in 4 cities, you can produce a total of 12 units in 3 turns. This make you save a lot of gold in units maintenance for a good amount of turns.
I just didn't realize the harbor needed to be in the capital as well since it says that it creates a city connection with the capital, and doesn't mention that your capital needs one too. I just figured I could get away without one
tr '\n' '\\n' would change newlines to backslashes (and then there's an extra n in the second set). sed 's/\n/\\n/g won't work because sed doesn't load the line-terminating newline into the buffer, but handles it internally.
This proposal is deeply flawed and would have far-reaching consequences if implemented. In #31148 I proposed a strategy to address the same pain points in a correct, more generic way. Regardless of whether my approach is taken or not, async handling of promises is a core feature that simply cannot be deprecated, and we should remove the erroneous deprecation accordingly.
NODE_OPTIONS=--unhandled-rejections=none node
There are other pjax implementations floating around, but most of them are jQuery-based or overengineered. Hence simple-pjax.
As said in the chapter, there’s an "implicit try..catch" around the function code. So all synchronous errors are handled. But here the error is generated not while the executor is running, but later. So the promise can’t handle it.
new Promise(function(resolve, reject) { setTimeout(() => { throw new Error("Whoops!"); }, 1000); }).catch(alert);
You cannot try/catch the reactive statement ($: has no effect outside of the top-level) window.onerror does not catch it window.onunhandledrejection does not catch it
.
The best you can do is try/catch inside a function that is reactively called, but my goal is to have a global exception handler to handle all exceptions that I did not expect...
It's vanilla JS, doesn't bind you to specifc syntax and that's the main reason why I like svelte that it doesn't try to sandbox you into framework constraints.
const originalUnhandledRejection = window.onunhandledrejection; window.onunhandledrejection = (e) => { console.log('we got exception, but the app has crashed', e); // or do Sentry.captureException(e); originalUnhandledRejection(e); }
If at least one component has smallest unhandled error, the whole app will crash and users will not know what to do and developers will not know such an error occurred.
When an error is thrown inside a Promise it looks like Firefox still calls window.onerror, but Chrome swallows the error silently.
Maybe once the core onError lifecycle is implemented (if maintainers decide to go that way) everyone will discover you're right and an implementation will be built in. I think that's probably what's going to happen. But until real life has proved it, it's usually best to go for the smallest most broadly applicable solution. I can definitely imagine <svelte:error> eventually being a thing, but it's a pretty dramatic change compared to an added importable function.
Having a consistent and predictable pattern is key to the elegance.
I think the issue is that it's not totally perfect. It doesn't define what should happen in parent components, it's not as flexible as onError and it doesn't allow you (for instance) to nest a svelte:head inside, or decide what to do with the rest of the rendering. What do you do with <div>My component</div> in your example? What about changing the <title>? I assume you can inspect the error...does <svelte:error> allow specifying which error types to expect?
That's like the example i wrote, and i think it's very ugly. It's annoying when frameworks are very elegant in demos and presentations but then that elegance disappear when you have to write real world code.
An annoying thing about frameworks is when they get too opinonated, which is, in my view, a problem React has.
const unsubscribe = errorStore.subscribe(value => { if (!value) { return } error = value errorStore.set() })
Boilerplate is only boilerplate if it's the same everywhere, which it shouldn't be.
Additionally, if you're writing a notification display in every single component, wrapped in a <svelte:error> tag, that's the very definition of boilerplate.
In other words, adding a svelte:error tag wouldn't help much.
and if I think this is too boilerplatey, I can export a handler from some .js file and pass the error to that: <script> import { onError } from 'svelte' import { genericHandler } from '../my-error-handler.js' onError(genericHandler(e => { // code which is called first to try to handle this locally return true // we've handled it here, don't do anything else. }) </script>
If a developer wants to handle the error inside the component and also wants to have it bubble up, they can use this.fire('error', e) within onerror.
So it is safe to use an async function as the callback argument to setTimer and setInterval. You just need toBe sure to wrap any operations that can throw an exception in a try/catch block andBe aware that the timer will not await on the promise returned by your async function
My gut told me calling an async function from the setTimeout callback was a bad thing. Since the setTimeout machinery ignores the return value of the function, there is no way it was awaiting on it. This means that there will be an unhandled promise. An unhandled promise could mean problems if the function called in the callback takes a long time to complete or throws an error.
The callback executed by setTimeout is not expected to return anything, it just ignores the returned value. Since once you enter the promise/async world in JavaScript you cannot escape, I was left to wonder what happens when the setTimeout callback returns a promise?
test2 being marked async does wrap your return value in a new promise:
const rejectedP = Promise.reject('-'); const finallyP = rejectedP.finally(); const result1 = rejectedP; const result2 = new Promise(resolve => { const rejectedP = Promise.reject('-'); const finallyP = rejectedP.finally(); resolve(rejectedP); }); we can see that the first snippet creates two promises (result1 and rejectedP being the same) while the second snippet creates three promises. All of these promises are rejected, but the rejectedP rejection is handled by the callbacks attached to it, both through ….finally() and resolve(…) (which internally does ….then(resolve, reject)). finallyP is the promise whose rejection is not handled in the both examples. In the second example, result2 is a promise distinct from rejectedP that is also not handled, causing the second event.
You basically did var a = promise.then(…); var b = promise.catch(…); creating a branch in the chain. If promise is getting rejected now, the catch callback will be called and b will be a fulfilled promise just fine, but the a promise is getting rejected too and nobody handles that. Instead, you should use both arguments of then and write Requirement.create({id: id, data: req.body.data, deleted: false}) .then(requirement => { res.json(requirement); }, reason => { let err = {'error': reason}; res.json(err); });
Updates/edits based on comments should preferably be reflected in the question itself. This way other readers don't have to weed out the whole comment section. You find the edit option under the question.
Just "ignoring" a Promise result if it is not longer needed is an antipattern in my opinion.
Moving forward I'd rather see {#await} being removed than adding more {#await}. But that's just from my experience and I'm sure there are use-cases for it.
I personally abstract everything away into stores. Stores are amazing. With everything I mean things like fetch, Worker or WebSocket.
Another limitation is that you are forced into the syntax of the {#await} block. What I mean by that is that for example you can't add a loading class to a parent. You can only render stuff for the loading state in the given block. Nowhere else.
export const fibonacci = function (n, initialData) { return readable( { loading: true, error: null, data: initialData, }, (set) => { let controller = new AbortController(); (async () => { try { let result = await fibonacciWorker.calculate(n, { signal: controller.signal }); set({ loading: false, error: null, data: result, }); } catch (err) { // Ignore AbortErrors, they're not unexpected but a feature. // In case of abortion we just keep the loading state because another request is on its way anyway. if (err.name !== 'AbortError') { set({ loading: false, error: err, data: initialData, }); } } })(); return () => { controller.abort(); }; } ); };
<script> import { fibonacci } from './math.js'; $: result = fibonacci(n, 0); </script> <input type=number bind:value={n}> <p>The {n}th Fibonacci number is {$result.data}</p> {#if $result.loading} <p>Show a spinner, add class or whatever you need.</p> <p>You are not limited to the syntax of an #await block. You are free to do whatever you want.</p> {/if}
Once you've written the imperative library/util code once, your components are super slim and completely reactive/declarative. Wow.
Yes I love stores.
No need to debounce fetch (terrible UX), just fire them away
export const load: Load = async ({ page, session }) => { if (!isPublic(page.path) && !isAuthenticated(session)) { console.log('Unauthorized access to private page'); return { redirect: '/', status: 302 }; } else { console.log('Auth OK'); } return {}; };
That whole setup works. If the user logs out, I can just write an empty JWT cookie and clear the $session.jwt value, redirect back to the home page, done.
In hooks.js I have a handle function that basically does request.locals.jwt = cookies.jwt, and then a getSession function that returns { jwt: locals.jwt }
Persisting across apps Your notifications can persist across multiple apps / page reloads, as long as they use this library. This is useful for a scenario where you show a notification and then redirect the browser to a different application, or trigger a full reload of the page. This is completely automatic and uses session storage.