Created
May 29, 2019 18:41
-
-
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
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
# 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 } |
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/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