Created
March 26, 2018 09:02
-
-
Save ArturT/023bf1977fe139e2d19164b86e3cb758 to your computer and use it in GitHub Desktop.
How to use http://dry-rb.org/gems/dry-struct/ and http://dry-rb.org/gems/dry-types/built-in-types/ to ensure params structure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/initializers/dry.rb | |
require 'dry-struct' | |
module Types | |
include Dry::Types.module | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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