### Install Marten from Sources Source: https://github.com/martenframework/marten/blob/main/docs/docs/getting-started/installation.md Install Marten by cloning the repository, installing dependencies, and building the CLI from source. ```bash git clone https://github.com/martenframework/marten cd marten shards install crystal build src/marten_cli.cr -o bin/marten mv bin/marten /usr/local/bin ``` -------------------------------- ### Marten Pagination Example Source: https://github.com/martenframework/marten/blob/main/docs/docs/models-and-databases/queries.md Demonstrates how to use Marten's pagination mechanism to retrieve and iterate over records split across pages. Shows how to get paginator metadata and access individual pages. ```crystal query_set = Article.filter(published: true) paginator = query_set.paginator(10) paginator.page_size # => 10 paginator.pages_count # => 6 paginator.total_count # => 60 # Retrieve the first page and iterate over the underlying records page = paginator.page(1) page.each { |article| puts article } page.number # 1 page.previous_page? # => false page.previous_page_number # => nil page.next_page? # => true page.next_page_number # => 2 page.total_count # => 60 ``` -------------------------------- ### Start Local Development Server Source: https://github.com/martenframework/marten/blob/main/docs/README.md Starts a local development server for live preview. Changes are reflected without a server restart. ```bash $ yarn start ``` -------------------------------- ### Install Crystal using APT Source: https://github.com/martenframework/marten/blob/main/docs/docs/getting-started/installation.md Install Crystal on Ubuntu, Debian, or other APT-based Linux distributions. ```bash curl -fsSL https://crystal-lang.org/install.sh | sudo bash ``` -------------------------------- ### Example Output of 'marten help' Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/management-commands.md An example of the output when running 'marten help', showing the usage pattern and a list of available commands. ```bash Usage: marten [command] [options] [arguments] Available commands: [marten] › clearsessions Clear all expired sessions. › collectassets Collect all the assets and copy them in a unique storage. › gen / g Generate various structures, abstractions, and values within an existing project. › genmigrations Generate new database migrations. › listmigrations List all database migrations. › migrate Run database migrations. › new Initialize a new Marten project or application repository. › play Start a Crystal playground server initialized for the current project. › resetmigrations Reset an existing set of migrations into a single one. › routes Display all the routes of the application. › seed Populate the database by running the seed file. › serve / s Start a development server that is automatically recompiled when source files change. › version Show the Marten version. Run a command followed by --help to see command specific information, ex: marten [command] --help ``` -------------------------------- ### Install Crystal Source: https://github.com/martenframework/marten/blob/main/docs/docs/deployment/how-to/deploy-to-an-ubuntu-server.md Installs Crystal on an Ubuntu server using the official installation script. Ensure you have sudo permissions. ```bash curl -fsSL https://crystal-lang.org/install.sh | sudo bash ``` -------------------------------- ### Install Crystal and Shards using Pacman Source: https://github.com/martenframework/marten/blob/main/docs/docs/getting-started/installation.md Install Crystal and the 'shards' command-line tool on ArchLinux and its derivatives using Pacman. ```bash sudo pacman -S crystal shards ``` -------------------------------- ### Marten Generator Help Output Example Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/generators.md Provides an example of the output when listing available generators, including common generators and usage instructions. ```bash Usage: marten gen [options] [generator] Generate various structures, abstractions, and values within an existing project. Arguments: generator Name of the generator to use Options: --error-trace Show full error trace (if a compilation is involved) --no-color Disable colored output -h, --help Show this help Available generators are listed below. [marten] › app › auth › email › handler › model › schema › secretkey Run a generator followed by --help to see generator specific information, ex: marten gen [generator] --help ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/martenframework/marten/blob/main/docs/README.md Installs project dependencies using Yarn. This is the first step before running any other commands. ```bash $ yarn ``` -------------------------------- ### Start Marten Playground Server Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/reference/management-commands.md Starts the Crystal playground server for the current project. Use --open to automatically open it in the default browser. ```bash marten play ``` ```bash marten play --open ``` -------------------------------- ### Start Marten Development Server (Alias) Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/reference/management-commands.md Starts the development server using the 's' alias. This is a shortcut for the 'marten serve' command. ```bash marten s ``` -------------------------------- ### Start Marten Development Server Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/reference/management-commands.md Starts a development server that recompiles automatically when source files change. Use --open to automatically open it in the default browser or specify a custom port. ```bash marten serve ``` ```bash marten serve -p 3000 ``` ```bash marten serve --open ``` -------------------------------- ### Start and Restart SystemD Service Source: https://github.com/martenframework/marten/blob/main/docs/docs/deployment/how-to/deploy-to-an-ubuntu-server.md Commands to start and restart the SystemD service for the application. Use 'start' for the initial launch and 'restart' for subsequent updates. ```bash service start ``` ```bash service restart ``` -------------------------------- ### Install Crystal using Homebrew Source: https://github.com/martenframework/marten/blob/main/docs/docs/getting-started/installation.md Install Crystal on macOS or Linux using the Homebrew package manager. ```bash brew install crystal ``` -------------------------------- ### Install Marten CLI using Homebrew Source: https://github.com/martenframework/marten/blob/main/docs/docs/getting-started/installation.md Install the Marten CLI tool on macOS or Linux using Homebrew. ```bash brew tap martenframework/marten brew trust martenframework/marten brew install marten ``` -------------------------------- ### Install Required Packages Source: https://github.com/martenframework/marten/blob/main/docs/docs/deployment/how-to/deploy-to-an-ubuntu-server.md Installs essential packages like git, nginx, and postgresql on Ubuntu. These are needed for version control, serving the application, and database management. ```bash sudo apt-get install git nginx postgresql ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/martenframework/marten/blob/main/docs/docs/deployment/how-to/deploy-to-an-ubuntu-server.md Installs project dependencies using the 'shards' package manager. This command should be run from the project's root directory. ```bash shards install ``` -------------------------------- ### Install Marten CLI using AUR Source: https://github.com/martenframework/marten/blob/main/docs/docs/getting-started/installation.md Install the Marten CLI using an AUR helper like 'yay' on ArchLinux and its derivatives. ```bash yay -S marten ``` -------------------------------- ### Basic Marten Spec Example Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/testing.md A simple example of a Marten spec file. Always ensure that './spec_helper' is required at the top of your spec files to set up the testing environment correctly. ```crystal require "./spec_helper" describe MySuperAbstraction do describe "#foo" do it "returns bar" do obj = MySuperAbstraction.new obj.foo.should eq "bar" end end end ``` -------------------------------- ### List All Migrations for All Apps Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/reference/management-commands.md Lists all available database migrations for all installed applications. This command helps in understanding the current migration status across the project. ```bash marten listmigrations ``` -------------------------------- ### Basic Schema Migration Example Source: https://github.com/martenframework/marten/blob/main/docs/docs/models-and-databases/migrations.md Defines a migration to add a new column and remove an old one from the `press_article` table. ```crystal # Generated by Marten 0.1.0 on 2022-03-30 22:13:06 -04:00 class Migration::Press::V202203302213061 < Marten::Migration depends_on :press, "202203111822091_initial" def forward add_column :press_article, :rating, :int, null: true remove_column :press_article, :old_status end def backward # do something else end end ``` -------------------------------- ### Displaying Generator Help Information Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/generators.md Shows how to get specific help for a particular generator by appending the --help flag. ```bash marten gen [generator] --help ``` -------------------------------- ### Render a template with context Source: https://github.com/martenframework/marten/blob/main/docs/docs/templates/reference/tags.md Example demonstrating how a template can include another and utilize variables from the parent context. The output depends on the `name` variable provided. ```html Hello, {{ name }}! {% include "question.html" %} ``` -------------------------------- ### Example Asset Manifest JSON Source: https://github.com/martenframework/marten/blob/main/docs/docs/assets/introduction.md A sample JSON manifest file showing the mapping between original asset filenames and their fingerprinted counterparts. ```json { "app/home.css": "app/home.9495841be78cdf06c45d.css", "app/home.js": "app/home.9495841be78cdf06c45d.js" } ``` -------------------------------- ### Accept Arguments and Options in a Command Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/how-to/create-custom-commands.md Use the `#setup` method to define arguments and options for your command. Arguments are positional, while options use flags like `--option` or `-o`. ```crystal class MyCommand < Marten::CLI::Command help "Command that does something" @arg1 : String? @example : Bool = false def setup on_argument(:arg1, "The first argument") { |v| @arg1 = v } on_option("example", "An example option") { @example = true } end def run # Do something end end ``` -------------------------------- ### RecordDelete Handler Usage Source: https://github.com/martenframework/marten/blob/main/docs/versioned_docs/version-0.6/handlers-and-http/reference/generic-handlers.md Example of how to use the RecordDelete handler to delete a specific model record. It can be used with POST requests for deletion or GET requests to display a confirmation page. ```APIDOC ## RecordDelete Handler ### Description Handler allowing to delete a specific model record. This handler can be used to delete an existing model record by issuing a POST request. Optionally the handler can be accessed with a GET request and a template can be displayed in this case; this allows to display a confirmation page to users before deleting the record. ### Method POST or GET ### Endpoint (Not explicitly defined, depends on routing) ### Parameters (Not explicitly defined, depends on model and routing) ### Request Example ```crystal class ArticleDeleteHandler < Marten::Handlers::RecordDelete model Article template_name "articles/delete.html" success_route_name "article_delete_success" end ``` ### Response #### Success Response (302 Found) Redirects to the success route or URL. #### Response Example (Redirects to a specified route or URL) ``` -------------------------------- ### Complex Filters with AND and NOT using q Expressions Source: https://github.com/martenframework/marten/blob/main/docs/docs/models-and-databases/queries.md Combine `q` expressions using AND (`&`) and NOT (`-`) operators to build intricate filter logic. This example finds articles starting with 'Top' but not authored by 'John'. ```crystal Article.filter { (q(title__startswith: "Top") | q(title__startswith: "10")) & -q(author__first_name: "John") } ``` -------------------------------- ### Complex Filters with OR using q Expressions Source: https://github.com/martenframework/marten/blob/main/docs/docs/models-and-databases/queries.md Use the `q` method within filter blocks to combine conditions with logical OR. This example retrieves articles where the title starts with 'Top' or '10'. ```crystal Article.filter { q(title__startswith: "Top") | q(title__startswith: "10") } ``` -------------------------------- ### Filtering Relations with Field Predicate Types Source: https://github.com/martenframework/marten/blob/main/docs/docs/models-and-databases/queries.md Apply specific field predicate types (like `__startswith`) when filtering through relations. This example finds authors whose hometown name starts with 'New'. ```crystal Author.filter(author__hometown__name__startswith: "New") ``` -------------------------------- ### Create Project Folders Source: https://github.com/martenframework/marten/blob/main/docs/docs/deployment/how-to/deploy-to-an-ubuntu-server.md Creates the directory structure for your application and sets ownership to the deployment user. Replace with your application's name. ```bash sudo mkdir /srv/ sudo chown deploy:deploy /srv/ ``` -------------------------------- ### ANDing Multiple Field Predicates within a q Expression Source: https://github.com/martenframework/marten/blob/main/docs/docs/models-and-databases/queries.md When multiple field predicates are defined inside a single `q()` expression, they are combined using an implicit AND. This example filters for articles starting with 'Top' and authored by 'John Doe'. ```crystal Article.filter { q(title__startswith: "Top") & -q(author__first_name: "John", author__last_name: "Doe") } ``` -------------------------------- ### Start Marten Documentation Live Server Source: https://github.com/martenframework/marten/blob/main/docs/docs/the-marten-project/contributing.md Run the Docusaurus development server to preview documentation changes locally. Access the live server at http://localhost:3000/docs/. ```bash npm run start ``` -------------------------------- ### Create New Project with Database Configuration Source: https://github.com/martenframework/marten/blob/main/docs/versioned_docs/version-0.6/development/reference/management-commands.md Creates a new project repository structure with a preconfigured PostgreSQL database. ```bash marten new project myblog --database=postgresql ``` -------------------------------- ### Default Installed Apps Configuration Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/reference/settings.md An empty array representing the default configuration for installed Marten applications. ```crystal [] of Marten::Apps::Config.class ``` -------------------------------- ### Implement a Custom File System Storage Source: https://github.com/martenframework/marten/blob/main/docs/docs/files/how-to/create-custom-file-storages.md This example shows a custom file system storage implementation that reads and writes files to a specific folder on the local file system. It requires implementing methods for saving, deleting, opening, checking existence, retrieving size, and generating URLs for files. ```crystal require "file_utils" class FileSystem < Marten::Core::Storage::Base def initialize(@root : String, @base_url : String) end def delete(filepath : String) : Nil File.delete(path(filepath)) rescue File::NotFoundError raise Marten::Core::Storage::Errors::FileNotFound.new("File '#{filepath}' cannot be found") end def exists?(filepath : String) : Bool File.exists?(path(filepath)) end def open(filepath : String) : IO File.open(path(filepath), mode: "rb") rescue File::NotFoundError raise Marten::Core::Storage::Errors::FileNotFound.new("File '#{filepath}' cannot be found") end def size(filepath : String) : Int64 File.size(path(filepath)) end def url(filepath : String) : String File.join(base_url, URI.encode_path(filepath)) end def write(filepath : String, content : IO) : Nil new_path = path(filepath) FileUtils.mkdir_p(Path[new_path].dirname) File.open(new_path, "wb") do |new_file| IO.copy(content, new_file) end end private getter root private getter base_url private def path(filepath) File.join(root, filepath) end end ``` -------------------------------- ### Verify Marten CLI Installation Source: https://github.com/martenframework/marten/blob/main/docs/docs/getting-started/installation.md Check if the Marten CLI is installed and accessible by running the version command. ```bash marten -v ``` -------------------------------- ### Configure PostgreSQL Database with Options Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/reference/settings.md Demonstrates setting additional options for a PostgreSQL database, such as SSL mode. ```crystal config.database do |db| db.backend = :postgresql db.host = "localhost" db.name = "my_db" db.user = "my_user" db.password = "my_password" db.options = {"sslmode" => "disable"} end ``` -------------------------------- ### Deliver a Welcome Email Source: https://github.com/martenframework/marten/blob/main/docs/docs/emailing/introduction.md Initialize and deliver a WelcomeEmail instance synchronously. The configured emailing backend will handle the actual delivery. ```crystal email = WelcomeEmail.new(user) email.deliver ``` -------------------------------- ### Use Custom FileSystem Storage in Crystal Source: https://github.com/martenframework/marten/blob/main/docs/docs/files/managing-files.md Shows how to initialize and use a custom FileSystem storage with a specified root and base URL. This allows for flexible file management outside the default media storage. ```crystal file = File.open("test.txt") storage = Marten::Core::Storage::FileSystem.new(root: "/tmp", base_url: "/tmp") filepath = storage.save("test.txt", file) storage.exists?(filepath) # => true storage.exists?("unknown") # => false storage.size(filepath) # => 13 storage.url(filepath) # => "/tmp/test.txt" storage.delete(filepath) # => nil storage.exists?(filepath) # => false ``` -------------------------------- ### Configure Installed Applications Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/applications.md Specify the list of Marten applications to be installed in a project by adding their respective classes to the 'installed_apps' configuration setting. ```crystal Marten.configure do |config| config.installed_apps = [ FooApp, BarApp, ] end ``` -------------------------------- ### Create New Marten Project with PostgreSQL Database Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/reference/management-commands.md Initializes a new Marten project and preconfigures it with a PostgreSQL database. ```bash marten new project myblog --database=postgresql ``` -------------------------------- ### Filter by string starting (case-sensitive) Source: https://github.com/martenframework/marten/blob/main/docs/docs/models-and-databases/reference/query-set.md Use `startswith` to filter records where a field's value starts with a specific substring. This is case-sensitive. ```crystal Article.all.filter(title__startswith: "Top") ``` -------------------------------- ### Initialize FileSystem Loader Source: https://github.com/martenframework/marten/blob/main/docs/docs/templates/reference/loaders.md Use this loader to retrieve templates directly from a specified directory on the file system. Provide the root template directory path during initialization. ```crystal loader = Marten::Template::Loader::FileSystem.new("/path/to/templates") ``` -------------------------------- ### Deploy application to Fly.io Source: https://github.com/martenframework/marten/blob/main/docs/docs/deployment/how-to/deploy-to-fly-io.md Upload your application's code to Fly.io. This command builds a Docker image, pushes it to the registry, and launches a container. ```bash fly deploy ``` -------------------------------- ### Install Marten Dependencies Source: https://github.com/martenframework/marten/blob/main/docs/docs/the-marten-project/contributing.md Install the necessary Crystal shards and Node.js dependencies for Marten development. This command also handles documentation dependencies. ```bash make ``` -------------------------------- ### Generate New Application Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/generators.md Creates a new Marten application named 'blogging'. ```bash marten gen app blogging ``` -------------------------------- ### Configure Installed Apps Source: https://github.com/martenframework/marten/blob/main/docs/docs/models-and-databases/introduction.md Configures Marten to include a custom application (`MyApp`) in the list of installed applications. This ensures models from this app are recognized. ```crystal Marten.configure do |config| config.installed_apps = [ MyApp, # other apps... ] end ``` -------------------------------- ### Implement an In-Memory Cache Store Source: https://github.com/martenframework/marten/blob/main/docs/docs/caching/how-to/create-custom-cache-stores.md This example demonstrates how to create a custom in-memory cache store by inheriting from `Marten::Cache::Store::Base` and implementing the necessary methods to manage cache entries in a hash. ```crystal class MemoryStore < Marten::Cache::Store::Base @data = {} of String => String def initialize( @namespace : String? = nil, @expires_in : Time::Span? = nil, @version : Int32? = nil, @compress = false, @compress_threshold = DEFAULT_COMPRESS_THRESHOLD ) super end def clear : Nil @data.clear end def decrement( key : String, amount : Int32 = 1, expires_at : Time? = nil, expires_in : Time::Span? = nil, version : Int32? = nil, race_condition_ttl : Time::Span? = nil, compress : Bool? = nil, compress_threshold : Int32? = nil ) apply_increment( key, amount: -amount, expires_at: expires_at, expires_in: expires_in, version: version, race_condition_ttl: race_condition_ttl, compress: compress, compress_threshold: compress_threshold ) end def increment( key : String, amount : Int32 = 1, expires_at : Time? = nil, expires_in : Time::Span? = nil, version : Int32? = nil, race_condition_ttl : Time::Span? = nil, compress : Bool? = nil, compress_threshold : Int32? = nil ) : Int apply_increment( key, amount: amount, expires_at: expires_at, expires_in: expires_in, version: version, race_condition_ttl: race_condition_ttl, compress: compress, compress_threshold: compress_threshold ) end private getter data private def apply_increment( key : String, amount : Int32 = 1, expires_at : Time? = nil, expires_in : Time::Span? = nil, version : Int32? = nil, race_condition_ttl : Time::Span? = nil, compress : Bool? = nil, compress_threshold : Int32? = nil ) normalized_key = normalize_key(key.to_s) entry = deserialize_entry(read_entry(normalized_key)) if entry.nil? || entry.expired? || entry.mismatched?(version || self.version) write( key: key, value: amount.to_s, expires_at: expires_at, expires_in: expires_in, version: version, race_condition_ttl: race_condition_ttl, compress: compress, compress_threshold: compress_threshold ) amount else new_amount = entry.value.to_i + amount entry = Entry.new(new_amount.to_s, expires_at: entry.expires_at, version: entry.version) write_entry(normalized_key, serialize_entry(entry)) new_amount end end private def delete_entry(key : String) : Bool deleted_entry = @data.delete(key) !!deleted_entry end private def read_entry(key : String) : String? data[key]? end private def write_entry( key : String, value : String, expires_in : Time::Span? = nil, race_condition_ttl : Time::Span? = nil ) data[key] = value true end end ``` -------------------------------- ### Filter by string starting (case-insensitive) Source: https://github.com/martenframework/marten/blob/main/docs/docs/models-and-databases/reference/query-set.md Use `istartswith` to filter records where a field's value starts with a specific substring, ignoring case. ```crystal Article.all.filter(title__istartswith: "top") ``` -------------------------------- ### Initialize and Setup Marten Project in Playground Source: https://github.com/martenframework/marten/blob/main/docs/docs/getting-started/tutorial.md Boilerplate code for the Marten playground. It requires project dependencies and sets up Marten. Subsequent code snippets should be added below this. ```crystal require "./src/project" # Setup the project. Marten.setup # Write your code here. ``` -------------------------------- ### Fly.io Application Configuration Source: https://github.com/martenframework/marten/blob/main/docs/docs/deployment/how-to/deploy-to-fly-io.md Example `fly.toml` file content generated by `fly launch`. It defines the app name, primary region, environment variables, and service settings. ```toml app = "" primary_region = "" [env] MARTEN_ALLOWED_HOSTS = ".fly.dev" [http_service] internal_port = 8000 force_https = true auto_stop_machines = true auto_start_machines = true ``` -------------------------------- ### Create New Marten Application Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/reference/management-commands.md Initializes a new Marten application repository structure with the specified name. ```bash marten new app auth ``` -------------------------------- ### Listing Available Generators Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/generators.md Demonstrates how to list all generators available within the current Marten project. ```bash marten gen ``` -------------------------------- ### Fetch Single Record with `get!` Source: https://github.com/martenframework/marten/blob/main/docs/docs/models-and-databases/raw-sql.md Use the `get!` method with raw SQL predicates to retrieve a single record. Raises an exception if no record is found. ```crystal article = Article.get!("title = :title AND created_at > :created_at", title: "Hello World!", created_at: "2022-10-30") ``` -------------------------------- ### Fetch Single Record with `get` Source: https://github.com/martenframework/marten/blob/main/docs/docs/models-and-databases/raw-sql.md Use the `get` method with raw SQL predicates to retrieve a single record. Returns `nil` if no record matches. ```crystal article = Article.get("title = ? AND created_at > ?", "Hello World!", "2022-10-30") ``` -------------------------------- ### Article Spec Example with Nested Helper Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/testing.md An example spec file for an Article model, utilizing a nested spec_helper.cr for its directory. This demonstrates how to structure specs within organized folders. ```crystal require "./spec_helper" describe Article do # ... end ``` -------------------------------- ### Create New Marten Project Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/reference/management-commands.md Initializes a new Marten project repository structure with the specified name. ```bash marten new project myblog ``` -------------------------------- ### Apply Database Migrations Source: https://github.com/martenframework/marten/blob/main/docs/docs/deployment/introduction.md Run this command to create or update database tables based on your project's models. Ensure you have compiled the `manage` binary. ```bash bin/manage migrate ``` -------------------------------- ### Simulate GET Request and Verify Response Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/testing.md Use the test client to perform a GET request and assert the status code and Location header of the response. This is useful for testing redirects. ```crystal describe MyRedirectHandler do describe "#get" do it "returns the expected redirect response" do response = Marten::Spec.client.get("/my-redirect-handler", query_params: {"foo" => "bar"}) response.status.should eq 302 response.headers["Location"].should eq "/redirected" end end end ``` -------------------------------- ### Define a Basic Management Command Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/how-to/create-custom-commands.md Subclass Marten::CLI::Command and define a `#run` method to implement command logic. Use the `#help` class method to set the command's help text. ```crystal class MyCommand < Marten::CLI::Command help "Command that does something" def run # Do something end end ``` -------------------------------- ### Run the Marten Server Source: https://github.com/martenframework/marten/blob/main/docs/docs/deployment/introduction.md Start the Marten development server. It's recommended to run this behind a reverse proxy like Nginx in production, and avoid using HTTP port 80. ```bash bin/server ``` -------------------------------- ### Retrieve a Specific Record by ID or Field Source: https://github.com/martenframework/marten/blob/main/docs/docs/models-and-databases/queries.md Use the `#get` method to retrieve a single record by its primary key or other fields. Returns `nil` if not found. Use `#get!` to raise an error if not found. ```crystal Author.get(id: 1) Author.get(first_name: "John") ``` -------------------------------- ### Resolve URL and Simulate GET Request Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/testing.md Demonstrates how to dynamically resolve a handler URL using Marten's routing before making a GET request with the test client. This avoids hardcoding paths. ```crystal url = Marten.routes.reverse("article_detail", pk: 42) response = Marten::Spec.client.get(url, query_params: {"foo" => "bar"}) ``` -------------------------------- ### Retrieve a single model instance with `get!` Source: https://github.com/martenframework/marten/blob/main/docs/versioned_docs/version-0.6/models-and-databases/reference/query-set.md Use `get!` to retrieve a single record, raising `RecordNotFound` if no record is found or `MultipleRecordsFound` if more than one record matches. This method is useful when you expect a record to exist. ```crystal query_set = Post.all post_1 = query_set.get!(id: 123) post_2 = query_set.get!(id: 456, is_published: false) ``` ```crystal query_set = Post.all post_1 = query_set.get! { q(id: 123) } post_2 = query_set.get! { q(id: 456, is_published: false) } ``` ```crystal Author.get!("id=?", 42) Author.get!("id=:id", id: 42) ``` -------------------------------- ### Create and Set Permissions for settings.env Source: https://github.com/martenframework/marten/blob/main/docs/docs/deployment/how-to/deploy-to-an-ubuntu-server.md Create an empty settings.env file and set its permissions. This file is used to store environment-specific settings. ```bash touch /srv//settings.env chmod 600 /srv//settings.env ``` -------------------------------- ### Retrieve a single model instance with `get` Source: https://github.com/martenframework/marten/blob/main/docs/versioned_docs/version-0.6/models-and-databases/reference/query-set.md Use `get` to retrieve a single record by its primary key or a unique field. It returns `nil` if no record is found and raises `MultipleRecordsFound` if more than one record matches. ```crystal query_set = Post.all post_1 = query_set.get(id: 123) post_2 = query_set.get(id: 456, is_published: false) ``` ```crystal query_set = Post.all post_1 = query_set.get { q(id: 123) } post_2 = query_set.get { q(id: 456, is_published: false) } ``` ```crystal Author.get("id=?", 42) Author.get("id=:id", id: 42) ``` -------------------------------- ### Example Template for Article Detail Source: https://github.com/martenframework/marten/blob/main/docs/docs/handlers-and-http/generic-handlers.md An example HTML template that displays details of an Article record fetched by the RecordDetail handler. It accesses the record's attributes like title and created_at from the 'record' context variable. ```html
  • Title: {{ record.title }}
  • Created at: {{ record.created_at }}
``` -------------------------------- ### Generated Migration File Example Source: https://github.com/martenframework/marten/blob/main/docs/docs/models-and-databases/migrations.md A sample migration file generated by Marten, detailing the addition of a 'hometown' column to the 'blog_author' table. It specifies dependencies and the migration plan. ```crystal # Generated by Marten 0.1.0 on 2022-06-22 18:56:24 -04:00 class Migration::Blog::V202206221856241 < Marten::Migration depends_on :blog, "202205290942181_previous_migration_name" def plan add_column :blog_author, :hometown, :string, max_size: 255, null: true end end ``` -------------------------------- ### Apply All Migrations Source: https://github.com/martenframework/marten/blob/main/docs/docs/development/reference/management-commands.md Applies all pending migrations for all installed applications. This is the default behavior when no arguments are provided. ```bash marten migrate # Applies all the non-applied migrations for all the installed apps ``` -------------------------------- ### Example HTML for List Inclusion Tag Source: https://github.com/martenframework/marten/blob/main/docs/docs/templates/how-to/create-custom-tags.md This HTML template is rendered by the `ListTag` to display list items. ```html
    {% for item in list %}
  • {{ item }}
  • {% endfor %}
``` -------------------------------- ### Generate New Project with Authentication Source: https://github.com/martenframework/marten/blob/main/docs/docs/authentication/introduction.md Use the `--with-auth` option with the `marten new` command to generate a new project that includes the authentication application. ```bash marten new project myblog --with-auth ``` -------------------------------- ### Create New Project Without Database Configuration Source: https://github.com/martenframework/marten/blob/main/docs/versioned_docs/version-0.6/development/reference/management-commands.md Creates a new project repository structure without any preconfigured database. ```bash marten new project myblog --database=none ``` -------------------------------- ### Customizing QuerySet for Record Update Source: https://github.com/martenframework/marten/blob/main/docs/docs/handlers-and-http/reference/generic-handlers.md Customize the queryset to filter records before updating, for example, by associating them with the current user. ```crystal class ArticleUpdateHandler < Marten::Handlers::RecordUpdate queryset Article.filter(user: request.user) schema ArticleUpdateSchema template_name "articles/update.html" success_route_name "my_form_success" end ``` -------------------------------- ### Get Primary Key Values Source: https://github.com/martenframework/marten/blob/main/docs/docs/models-and-databases/reference/query-set.md Retrieves an array of primary key values for all records targeted by the query set. ```crystal Post.all.pks # => [1, 2, 3] ``` -------------------------------- ### Including Partial Templates Source: https://github.com/martenframework/marten/blob/main/docs/docs/templates/introduction.md Demonstrates how to include partial templates with and without additional context variables. ```html {% include "partials/button.html" with type="primary" %} {% include "partials/button.html" with type="primary", text="Custom text" %} ``` ```html {% include "partials/other_snippet.html" %} ```