Skip to content

Instantly share code, notes, and snippets.

@gosukiwi
Created May 29, 2019 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gosukiwi/3b96e6c7f3ff7692b818650354f12c90 to your computer and use it in GitHub Desktop.
Save gosukiwi/3b96e6c7f3ff7692b818650354f12c90 to your computer and use it in GitHub Desktop.
Custom predicates for Ransack, allows you to search inside a YAML-serialized Array column
# some model
serialize :my_field, Array
ransacker :my_field_raw, type: :string do
Arel.sql('my_table.my_field')
end
# some view (using simple form)
= search_form_for @q, builder: SimpleForm::FormBuilder do |f|
= f.input :my_field_raw_yaml_array_matches_all, collection: [...], input_html: { multiple: true }
# config/initializers/ransack.rb
def arrayable?(value)
value.present? && (value.is_a?(Array) || JSON.parse(value).is_a?(Array))
rescue
false
end
def to_array(value)
return value if value.is_a?(Array)
JSON.parse(value)
end
Ransack.configure do |config|
config.add_predicate 'yaml_array_matches_all',
arel_predicate: 'matches_all',
formatter: proc { |value|
to_array(value).map do |v|
"%- '#{v.strip}'\n%"
end
},
validator: proc { |value| arrayable?(value) },
type: :string
config.add_predicate 'yaml_array_does_not_match_any',
arel_predicate: 'does_not_match_any',
formatter: proc { |value|
to_array(value).map do |v|
"%- '#{v.strip}'\n%"
end
},
validator: proc { |value| arrayable?(value) },
type: :string
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment