Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bhserna/76e6d75ba01b37c742fd15896644da22 to your computer and use it in GitHub Desktop.
Save bhserna/76e6d75ba01b37c742fd15896644da22 to your computer and use it in GitHub Desktop.
input = {
"builder_rule_0_filter"=>"artist_name",
"builder_rule_0_operator"=>"contains",
"builder_rule_0_value_0"=>"New Found Glory",
"builder_rule_1_filter"=>"bpm",
"builder_rule_1_operator"=>"less",
"builder_rule_1_value_0"=>"150",
"builder_rule_2_filter"=>"days_ago",
"builder_rule_2_operator"=>"less",
"builder_rule_2_value_0"=>"40",
"builder_rule_3_filter"=>"release_date_start",
"builder_rule_3_operator"=>"between",
"builder_rule_3_value_0"=>"2019-01-01",
"builder_rule_3_value_1"=>"2019-12-31",
}
Key = Struct.new(:id, :attr)
Rule = Struct.new(:filter, :operator, :values) do
def process_key!(key, value)
case key.attr
when "filter" then self.filter = value
when "operator" then self.operator = value
when "value"
self.values ||= []
values << value
end
end
def to_h
{ "filter" => filter,
"operator" => operator,
"values" => values.map.with_index { |v, i| [i, v] }.to_h }
end
end
rules = {}
input.each do |key, value|
key = Key.new(*key.split("_")[2..3])
rule = rules[key.id] ||= Rule.new
rule.process_key!(key, value)
end
rules.each do |key, value|
rules[key] = value.to_h
end
puts rules.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment