has_scope icon indicating copy to clipboard operation
has_scope copied to clipboard

Provide possible types to has_scope

Open baka-san opened this issue 2 years ago • 2 comments

I'm not sure if this is possible or if it is a feature request, but I'd like to be able to do something like has_scope :region_id, type: [:default, :array]. I don't necessarily know how the user will be passing the data so it could be an integer, e.g. ?region_id=1 or an array, e.g. ?region_id[]=1&region_id[]=2. I did try the following and it did NOT work.

has_scope :region_id, if: ->(request) { request.params[:region_id].is_a? String }
has_scope :region_id, type: :array, if: ->(request) { request.params[:region_id].is_a? Array }

baka-san avatar Aug 26 '22 14:08 baka-san

I put the following in config/initializers/has_scope.rb and it's allowing me to provide an array of allowed types. So...I can do has_scope :user_id, type: [:array, :default] and both ?user_id=1 and ?user_id[]=1&user_id[]=2 will be accepted in the controller. If this is a desired feature, I can submit a PR. If not, feel free to close the issue.

module HasScope
  protected

  # Allow an array of types to be passed, accepting the first matched in ALLOWED_TYPES.
  def parse_value(types, value)
    types = types.is_a?(Array) ? types : [types]

    types.each do |type|
      klasses, parser = ALLOWED_TYPES[type]

      if klasses.any? { |klass| value.is_a?(klass) }
        return parser ? parser.call(value) : value
      end
    end

    nil
  end
end

baka-san avatar Sep 04 '22 11:09 baka-san

I need this!

marcocarvalho avatar Feb 14 '23 13:02 marcocarvalho