marten-money 0.1.0

A custom :money model field that integrates the Money shard

Marten Money

Marten Money is a Crystal shard that integrates the Money library with the Marten web framework providing a new money field for handling monetary values in your models.

Features

  • Drop-in :money field type for Marten models
  • Accurate handling of monetary values using the Money type.
  • Automatic generation of database fields for amount and currency.
  • Support for multiple currencies with ISO 4217 codes.
  • Built-in validations via the Money class to ensure data integrity.

Installation

Add the shard to your shard.yml:

dependencies:
  marten_money:
    github: treagod/marten-money

Then, install the dependencies:

shards install

And require it in your src/project.cr:

require "marten_money"

Usage

class Invoice < Marten::Model
  field :id, :big_int, primary_key: true, auto: true

  field :total, :money, blank: false, null: false
end

Creating and Accessing the Money Field

You can create a new Invoice record with a Money object:

invoice = Invoice.create!(total: Money.new(10_00, "USD"))
# Or
invoice = Invoice.create!(
  total_amount: 10_00,
  total_currency: "USD"
)


# underlying columns
puts invoice.total_amount    # => 1000
puts invoice.total_currency  # => "USD"

Accessing the total field:

puts invoice.total.amount     # => 10.0
puts invoice.total.fractional # => 1000
puts invoice.total.currency   # => "USD"

puts invoice.total == Money.new(1000, "USD") # => true

Field Options

Option Type Default Description
blank Bool false Whether the field allows blank (empty) values.
null Bool false Whether the field allows NULL values in the database.
default Money nil Default value written as a literal, e.g. Money.new(1000, "USD").
amount_field_id String / Symbol :"<field>_amount" Overrides the name of the amount column.
currency_field_id String / Symbol :"<field>_currency" Overrides the name of the currency column.
store_currency Bool true If false, skips creating/storing the currency column.

Configuration

To configure the Money shard (e.g., set default currency, enable infinite precision), create a Marten initializer:

# config/initializers/money.cr

Money.default_currency = :cad
Money.infinite_precision = true

For more configuration options, refer to the Money shard documentation.

Contributing

Contributions are welcome! Please fork the repository and submit a pull request with your enhancements.

Repository

marten-money

Owner
Statistic
  • 1
  • 0
  • 1
  • 0
  • 4
  • 1 day ago
  • May 21, 2025
License

MIT License

Links
Synced at

Wed, 28 May 2025 08:58:26 GMT

Languages