Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide possible types to has_scope #124

Open
baka-san opened this issue Aug 26, 2022 · 3 comments
Open

Provide possible types to has_scope #124

baka-san opened this issue Aug 26, 2022 · 3 comments

Comments

@baka-san
Copy link

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
Copy link
Author

baka-san commented Sep 4, 2022

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

@marcocarvalho
Copy link

I need this!

@hidr0
Copy link

hidr0 commented Nov 6, 2024

I would also benefit from this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

3 participants