Skip to content

Instantly share code, notes, and snippets.

@ArturT
Created March 26, 2018 09:02
Show Gist options
  • Save ArturT/023bf1977fe139e2d19164b86e3cb758 to your computer and use it in GitHub Desktop.
Save ArturT/023bf1977fe139e2d19164b86e3cb758 to your computer and use it in GitHub Desktop.
# config/initializers/dry.rb
require 'dry-struct'
module Types
include Dry::Types.module
end
params = {
pricing_name: String,
start_date: String,
end_date: String,
selected_retailer_ids: [],
selected_product_ids: [],
filter_type: String, # percentage, value
filter_increase: true, #
filter_value: Integer, # can be only positive
manual_prices: [
{
retailer_id: Integer,
product_id: String, # it's product's code
new_price: Decimal,
}
]
}
# it will ensure the params have valid structure and types for manual prices
manual_prices = params[:manual_prices].map do |manual_price|
PricingManualPriceEntity.new(manual_price)
end
# we can cast to hash before saving to DB
manual_prices.to_h
# app/entities/pricing_manual_price_entity.rb
class PricingManualPriceEntity < Dry::Struct
# alternative Types::Coercible::Int will cast string id to int if params have ID as string
attribute :retailer_id, Types::Strict::Int
attribute :product_id, Types::String # Product code is a string
attribute :new_price, Types::Decimal
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment