Module: WhittakerTech::Midas::Paramable

Extended by:
ActiveSupport::Concern
Defined in:
app/controllers/concerns/whittaker_tech/midas/paramable.rb

Overview

Paramable provides Strong Params integration for Bankable coin attributes.

Mix into any controller that needs to permit and apply coin parameters. Accepts two input formats per role:

Combined — one field, colon-delimited minor units and ISO currency code:

price: "1245:USD"

Split — two fields, minor units and currency code separately:

price_minor: 1245, price_currency: "USD"

Both formats coerce to the same set_* call on the record. The combined format is convenient for JSON APIs; the split format matches what midas_currency_field emits from the browser.

Examples:

class ProductsController < ApplicationController
  include WhittakerTech::Midas::Paramable

  def create
    @product = Product.new(product_params.except(*coin_permit_keys(:price, :cost)))
    @product.save!
    assign_coins(@product, product_params, :price, :cost)
  end

  private

  def product_params
    params.require(:product).permit(:name, *coin_permit_keys(:price, :cost))
  end
end

Since:

  • 0.3.0

Constant Summary collapse

COMBINED_PATTERN =

Since:

  • 0.3.0

/\A(-?\d+):([A-Za-z]{3})\z/

Instance Method Summary collapse

Instance Method Details

#assign_coins(record, permitted_params, *roles) ⇒ Object

Calls set_#{role} on record for each role that has params present. Skips roles whose params are entirely absent; raises nothing for missing data.

Combined format takes priority when both formats appear for the same role.

Parameters:

  • record (ActiveRecord::Base)

    a model that includes Bankable

  • permitted_params (ActionController::Parameters, Hash)
  • roles (Array<Symbol>)

Since:

  • 0.3.0



64
65
66
67
68
69
# File 'app/controllers/concerns/whittaker_tech/midas/paramable.rb', line 64

def assign_coins(record, permitted_params, *roles)
  roles.each do |role|
    data = extract_coin(permitted_params, role)
    record.public_send(:"set_#{role}", **data) if data
  end
end

#coin_permit_keys(*roles) ⇒ Array<Symbol>

Returns the list of param field names to pass to ActionController::Parameters#permit for the given coin roles. Always includes keys for both formats so either works.

Examples:

coin_permit_keys(:price, :cost)
# => [:price, :price_minor, :price_currency, :cost, :cost_minor, :cost_currency]

Parameters:

  • roles (Array<Symbol>)

Returns:

  • (Array<Symbol>)

Since:

  • 0.3.0



52
53
54
# File 'app/controllers/concerns/whittaker_tech/midas/paramable.rb', line 52

def coin_permit_keys(*roles)
  roles.flat_map { |r| [r.to_sym, :"#{r}_minor", :"#{r}_currency"] }
end