Remove key, value pairs from a Hash given a condition.
Can be used to handle optional data from frontend filters.
user_options = {
theme: nil,
filters: [],
settings: :custom,
last_page: ""
}
user_options.delete_if { |_k, v| v.blank? }
#=> {:settings=>:custom}
class Options
include ActiveModel::Model
include ActiveModel::Attributes
attribute :theme, default: :dark
def initialize(attrs = {})
super(attrs.delete_if { |_k, v| v.blank? })
end
end
options_nil_theme = {
theme: nil
}
options = Options.new(options_nil_theme)
puts options.theme
#=> :dark
options_theme = {
theme: :light
}
options = Options.new(options_theme)
puts options.theme
#=> :light