Skip to main content

larust_support/
url_helper.rs

1/// Builds an absolute URL from `path`, using the app's configured
2/// `APP_URL` (Laravel's `url($path)`).
3pub fn url(path: &str) -> String {
4    join_url(&larust_core::config().app_url, path)
5}
6
7/// Laravel's `asset($path)` only differs from `url($path)` once a separate
8/// CDN/`ASSET_URL` is configured - no such concept exists in this
9/// framework yet, so this is a direct delegation, matching Laravel's own
10/// default behavior when no separate asset URL is set. A real, distinct
11/// implementation (and its own config field) is a natural addition if a
12/// CDN-hosted-assets need ever shows up.
13pub fn asset(path: &str) -> String {
14    url(path)
15}
16
17/// The actual joining logic, factored out from `url()` so it's testable
18/// without touching `larust_core::config()`'s process-wide `OnceLock`
19/// (which only `Application::new()` can populate, and only once per
20/// process - not practical to exercise per-test-case here). Normalizes
21/// exactly one `/` between `base` and `path` regardless of whether either
22/// side already has one, so `url("/posts")` and `url("posts")` produce the
23/// same result - callers don't need to remember which style this
24/// particular helper expects.
25fn join_url(base: &str, path: &str) -> String {
26    format!(
27        "{}/{}",
28        base.trim_end_matches('/'),
29        path.trim_start_matches('/')
30    )
31}
32
33#[cfg(test)]
34mod tests {
35    use super::*;
36
37    #[test]
38    fn joins_a_leading_slash_path_with_exactly_one_slash() {
39        assert_eq!(
40            join_url("http://example.test", "/posts"),
41            "http://example.test/posts"
42        );
43    }
44
45    #[test]
46    fn joins_a_path_with_no_leading_slash_the_same_way() {
47        assert_eq!(
48            join_url("http://example.test", "posts"),
49            "http://example.test/posts"
50        );
51    }
52
53    #[test]
54    fn joins_a_base_with_a_trailing_slash_without_doubling_it() {
55        assert_eq!(
56            join_url("http://example.test/", "/posts"),
57            "http://example.test/posts"
58        );
59    }
60
61    #[test]
62    fn empty_path_still_produces_a_trailing_slash_on_the_base() {
63        assert_eq!(join_url("http://example.test", ""), "http://example.test/");
64    }
65}