Giter VIP home page Giter VIP logo

rails_param's Introduction

rails_param

Parameter Validation & Type Coercion for Rails

Gem Version Build Status

Introduction

This library is handy if you want to validate a few numbers of parameters directly inside your controller.

For example : you are building a search action and want to validate that the sort parameter is set and only set to something like desc or asc.

Important

This library should not be used to validate a large number of parameters or parameters sent via a form or namespaced (like params[:user][:first_name]). There is already a great framework included in Rails (ActiveModel::Model) which can be used to create virtual classes with all the validations you already know and love from Rails. Remember to always try to stay in the “thin controller” rule.

See this page to see an example on how to build a contact form using ActiveModel::Model.

But sometimes, it’s not practical to create an external class just to validate and convert a few parameters. In this case, you may use this gem. It allows you to easily do validations and conversion of the parameters directly in your controller actions using a simple method call.

Credits

This is originally a port of the gem sinatra-param for the Rails framework.

All the credits go to @mattt.

It has all the features of the sinatra-param gem, I used bang methods (like param!) to indicate that they are destructive as they change the controller params object and may raise an exception.

Upgrading

Find a list of breaking changes in UPGRADING.

Installation

As usual, in your Gemfile...

  gem 'rails_param'

Example

  # GET /search?q=example
  # GET /search?q=example&categories=news
  # GET /search?q=example&sort=created_at&order=ASC
  def search
    param! :q,           String, required: true
    param! :categories,  Array
    param! :sort,        String, default: "title"
    param! :order,       String, in: %w(asc desc), transform: :downcase, default: "asc"
    param! :price,       String, format: /[<\=>]\s*\$\d+/

    # Access the parameters using the params object (like params[:q]) as you usually do...
  end
end

Parameter Types

By declaring parameter types, incoming parameters will automatically be transformed into an object of that type. For instance, if a param is :boolean, values of '1', 'true', 't', 'yes', and 'y' will be automatically transformed into true. BigDecimal defaults to a precision of 14, but this can but changed by passing in the optional precision: argument. Any $ and , are automatically stripped when converting to BigDecimal.

  • String
  • Integer
  • Float
  • :boolean/TrueClass/FalseClass ("1/0", "true/false", "t/f", "yes/no", "y/n")
  • Array ("1,2,3,4,5")
  • Hash ("key1:value1,key2:value2")
  • Date, Time, & DateTime
  • BigDecimal ("$1,000,000")

Validations

Encapsulate business logic in a consistent way with validations. If a parameter does not satisfy a particular condition, an exception (RailsParam::InvalidParameterError) is raised. You may use the rescue_from method in your controller to catch this kind of exception.

  • required
  • blank
  • is
  • in, within, range
  • min / max
  • min_length / max_length
  • format

Customize exception message with option :message

param! :q, String, required: true, message: "Query not specified"

Defaults and Transformations

Passing a default option will provide a default value for a parameter if none is passed. A default can defined as either a default or as a Proc:

param! :attribution, String, default: "©"
param! :year, Integer, default: lambda { Time.now.year }

Use the transform option to take even more of the business logic of parameter I/O out of your code. Anything that responds to to_proc (including Proc and symbols) will do.

param! :order, String, in: ["ASC", "DESC"], transform: :upcase, default: "ASC"
param! :offset, Integer, min: 0, transform: lambda {|n| n - (n % 10)}

Nested Attributes

rails_param allows you to apply any of the above mentioned validations to attributes nested in hashes:

param! :book, Hash do |b|
  b.param! :title, String, blank: false
  b.param! :price, BigDecimal, precision: 4, required: true
  b.param! :author, Hash, required: true do |a|
    a.param! :first_name, String
    a.param! :last_name, String, blank: false
  end
end

Arrays

Validate every element of your array, including nested hashes and arrays:

# primitive datatype syntax
param! :integer_array, Array do |array,index|
  array.param! index, Integer, required: true
end

# complex array
param! :books_array, Array, required: true  do |b|
  b.param! :title, String, blank: false
  b.param! :author, Hash, required: true do |a|
    a.param! :first_name, String
    a.param! :last_name, String, required: true
  end
  b.param! :subjects, Array do |s,i|
    s.param! i, String, blank: false
  end
end

Thank you

Many thanks to:

Contact

Nicolas Blanco

License

rails_param is available under the MIT license. See the LICENSE file for more info.

rails_param's People

Contributors

1075461847 avatar alexeyschepin avatar ccdredzik avatar cefigueiredo avatar claytonpassmore avatar crevete avatar davelooi avatar ifellinaholeonce avatar imactia avatar jlw avatar joevandyk avatar kmcgaire avatar liqrgv avatar petergoldstein avatar piya23300 avatar shhavel avatar stantoncbradley avatar viveksoundrapandi avatar vladucu avatar willian avatar yeeyee18 avatar zentooo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rails_param's Issues

Boolean type conversion issue

Basic Info

  • rails_param Version: 0.10.2
  • Ruby Version: ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin17]
  • Rails Version: 5.2.1

Issue description

Type conversion not working correctly for the boolean type and it raises TypeError. I think we need to handle that error if conversion is not possible. Because when we don't handle it, it raises internal server error.

Steps to reproduce

  • Create sample parameter
    param!(:example, Integer, required: true, blank: false)
  • Send following JSON as request body
    {
        "example": true
    } 
  • It raise an error like this:
    can't convert true into Integer
    
    /Users/bora/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/rails_param-0.10.2/lib/rails_param/param.rb:106:in `Integer'
    /Users/bora/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/rails_param-0.10.2/lib/rails_param/param.rb:106:in `coerce'
    /Users/bora/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/rails_param-0.10.2/lib/rails_param/param.rb:28:in `param!'

Empty string as default

The following:

param! :q, String, default: ""

does not seems to work. No q key is set in my params if I have an empty string as a default. It works if I use a non empty string

Wrong array to string coercion

Basic Info

  • rails_param Version: 1.3.0
  • Ruby Version: 3.1
  • Rails Version: 7.0

Issue description

We pass in our spec the following:

req[:orders_attributes][0][:email] = %w[[email protected] [email protected]]

And in our controller we validate this param with a:

   order.param! :email, String

With rails_param (0.11.2) and rails 6 the coercion happens. With rails_param (~> 1.3.0) it doesn't

Extract from pry session while running the spec:

RAILS 6

[3] pry(#<Api::ImportController>)> order.params["email"]
=> ["[email protected]", "[email protected]"]
[4] pry(#<Api::ImportController>)> 

[3] pry(#<Api::ImportController>)> order.param! :email, String
RailsParam::Param::InvalidParameterError: '["[email protected]", "[email protected]"]' is not a valid String
from /home/foo/.bundle/ruby/3.1.0/gems/rails_param-0.11.2/lib/rails_param/param.rb:134:in `rescue in coerce'
Caused by ArgumentError: ArgumentError
from /home/foo/.bundle/ruby/3.1.0/gems/rails_param-0.11.2/lib/rails_param/param.rb:106:in `coerce'

RAILS 7 and the gem 1.3.0, the exception doesn't get raised

[1] pry(#<Api::ImportController>)> order.params["email"]
=> ["[email protected]", "[email protected]"]
[2] pry(#<Api::ImportController>)> order.param! :email, String
=> "[\"[email protected]\", \"[email protected]\"]"
[3] pry(#<Api::Las::Scc::ImportController>)> 

For sure in that case I could simply validate by format, but I have more than 30 unique fails, since this is validated in many different parameters.

Steps to reproduce

I think passing an array like %w[[email protected] [email protected]] or as nested attributes like in my case (req[:orders_attributes][0][:email] ) having he validation as foo.param! :email, String should do the trick:

when nil in required param `transform` fails

Basic Info

  • rails_param Version: 0.11.0
  • Ruby Version: 2.6
  • Rails Version: 4.2.10

The following is a required param, if the param is missing a Parameter type is required (400) exception should be thrown. However, the transform executes before the required validation and to_sym throws undefined method to_sym for nil:NilClass.

param! :type, String, required: true, in: %i[quarterly annual], transform: :to_sym

"in" doesn't throw an error when unexpected value given

Basic Info

  • rails_param Version: 0.11.0
  • Ruby Version: ruby 2.6.3p62
  • Rails Version: Rails 6.0.0.rc2

Issue description

param! function doesn't throw a RailsParam::Param::InvalidParameterError if parameter value is not in the allowed values which specified with in argument.

Steps to reproduce

  1. Create a rails controller.
  2. Add this line to the controller method param! :order, String, %w(asc desc), default: 'asc'
  3. Call the controller method with ?order=neither_asc_nor_desc

Hash Conversion Issue

Basic Info

  • rails_param Version: 0.10.2
  • Ruby Version: 2.4.2
  • Rails Version: 4.2.11.1

Issue description

When an Integer, Float, Bool or another type without a split method is supplied when expecting a Hash an exception is thrown that is not caught by the ArgumentError rescue. For example, when passing a 1 instead of {} raises error:

undefined method `split' for 1:Integer

Steps to reproduce

Setup the params:

param! :person, Hash do |p|
 p.param! :name, String
end

Then send payload:

{
  "person": 1
}

Idea : migrate all validations to ActiveModel

Instead of using its own rules, rails_param could use a ActiveModel class to validate the params.
This would be a major rewrite of the library.
The benefit is that the developer will be able to use all the known validations he already uses, like:

param! :phone_number, String, presence: true, length: { minimum: 3 }

Typecasting and transformation will still be implemented internally (I could use some other gems like Virtus but for the moment I don't want dependencies).

It will also be possible for the developper to access the errors Hash.

when the param use default value, transform will not take effect

Basic Info

  • rails_param Version: 1.3.0
  • Ruby Version: 3.0.0
  • Rails Version: 7.0.2.3

Issue description

The following is a param with default and transform, When the default end date is used, transform will not take effect

param! :end_date, Date, default: Date.today, transform: ->(d) { !d.past? ? Date.yesterday : d }

I found the following snippet in the source code,

parameter.transform if params.include?(name) && options[:transform]

When the default end date is used,the params.include?(name) will return false because all operations so far have been performed on parameters, not params

Inner hash parameters are validated even when the outer hash is not required

Great gem, this reduces our validation complexity a lot!

  param! :person, Hash, required: false do |person|
    person.param! :name, String, required: true
  end

This fails when person (which is optional) is not provided because the person.name is missing.

Our solution is to wrap each of these in an extra if block but this seems like something this gem would want to handle internally.

  if params['person'].present?
    param! :person, Hash, required: false do |person|
      person.param! :name, String, required: true
    end
  end

Remove the "nested attributes" feature

I'm thinking of removing the "nested attributes" feature to stay in the philosophy of a minimalist gem.

To validate nested attributes you can do this easily with an ActiveModel::Model class. Also you can validate the presence of the nested objects using Strong parameters and the require method on the params object.

If you have any opinion on this, please comment!

rails_param loads the whole rails suite

Basic Info

rails_param loads the whole rails suite even when it is not needed.

  • rails_param Version: 1.2.0
  • Ruby Version: 3.0
  • Rails Version: 6.1

Issue description

In my project I don't need the whole rails suite. My Gemfile contains only the next rails gems.

gem 'actionpack', '~> 6.1'
gem 'activejob', '~> 6.1'
gem 'activemodel', '~> 6.1'
gem 'activerecord', '~> 6.1'
gem 'activesupport', '~> 6.1'

Unfortunately rails_param loads the whole rails suite including actioncable, actionmailer, etc..
I think it can be simply fixed by modifying gem specification to

s.add_development_dependency 'rspec', '~> 3.4'
s.add_development_dependency 'rspec-rails', '~> 3.4'

s.add_dependency 'actionpack', '>= 3.2.0'
s.add_dependency 'activesupport', '>= 3.2.0'

What is the point of having the whole rails dependency?

s.add_dependency 'rails', '>= 3.2.0'

Rails 5 No Method Error: Split

Hi,

I upgraded to rails 5 and found some errors:

param! :attributes, Hash, required: true do |b| b.param! :email, String, required: true b.param! :password, String, required: true end

would cause an error:

"title": "Unexpected Server Error. Try again later.", "message": "undefined method split' for #ActionController::Parameters:0x007f9d51b3c4a0",
"class": "NoMethodError",
"backtrace": [
"$GEMS/actionpack-5.0.1/lib/action_controller/metal/strong_parameters.rb:647:in method_missing'",

[CI] Review Rails versions matrix

Issue description

We currently test against different Ruby/Rails version combinations.
Some of these are EOL, as you can see here for Ruby and here for Rails.

Releasing v1.0 is a great opportunity to drop support for these.
Nothing forces us to support EOL'ed versions, although users with older applications will definitely appreciate the gesture, but if the codebase can potentially be simplified (with positive effects on the maintenance burden), then we should probably consider to drop at least a few of them.

After the release (or at the same time?) we should also consider adding 3.0 to the CI matrix and see if rails_param works with that as well.

Introduce an UPGRADING.md file

Issue description

We've recently merged some changes in master that will be released under v1.0 because they're breaking changes.
To make it easier for developers to upgrade, we should add an UPGRADING.md file (and mention it in the README?) so that they can quickly upgrade from 0.x to 1.0.

e.g. As a result of #66, namespaces have changes and this directly affect the RailsParam::InvalidParameterError class which was previously defined as RailsParam::Param::InvalidParameterError and thus rescued like this by users of this gem

Ignore blank values

I'd like to have an option something like ignore_blank: true

so with example

params = {
  period: ''
}
param! :period, String, in: %w(day week month), default: 'day', ignore_blank: true

the in validation won't be triggered

Support multiparameter attributes

It would be nice if this library supported the multiparameter attributes submitted by the following:

  • date_select
  • time_select
  • datetime_select

These inputs submit values that work nicely for models, but if you're trying to access that value in your controller, it's always really ugly because you have to do something like this:

Date.civil(params[:report]["start_date(1i)"].to_i,
           params[:report]["start_date(2i)"].to_i,
           params[:report]["start_date(3i)"].to_i)

support nested params

I know that nested params tends to usually happen when dealing with model-back resources, and that in those cases you're supposed to rely on your model validations.

However, that pattern doesn't work for me. I can't just stick the data into my model and call .validate!, because I'm validating far more than basic data types and values. I'm also validating complex inter-model relationships with the help of a Service object, and I need to type-and-value sanitize the params in the Controller before passing them to the Service object.

rails_param looks awesome, and would be of great help with this, except it only takes param names as a symbol, and therefore there's no way to handle nested params such as params[:user][:name].

Raising custom error messages

Basic Info

  • rails_param Version: 0.10.1
  • Ruby Version: 2.5.1
  • Rails Version: 5.2.0

Issue description

Big fan of this gem, reduces a lot of dev effort in validating parameters. One small thing I found out though: custom messages with message option does not work, it still throws up parameter XXX is required

Steps to reproduce

Taking the example in readme, if you do
param! :q, String, required: true, message: "Query not specified"

it still throws up: Parameter q is required instead of Query not specified

Need help with maintenance?

Hi @nicolasblanco,

just touching base with you regarding maintenance for rails_param.
I absolutely love this gem and I've been using for 2-3 years now, but I notice it's not easy for you to follow Issue/PRs.
As the main Faraday maintainer, I absolutely understand you probably have a lot of things to do and you're alone managing the gem.

I'm here to offer my help as a co-maintainer. I'm happy to review PR, triage Issue and even merge PR if you're OK with it. I'm also happy to leave release permissions to you only if you prefer to keep control of the release process.

I can see a lot of great ideas just waiting to be reviewed/merged but hanging forever, so rather than complaining I decided to offer my help.

Let me know your thoughts.

get a warning in rails5

i get a warning in rails5,"some methods will be remove in rails5.1",Please consider compatibility in rails5

Nested param

Hello,

I have a form_for, named :my_form inside a view and all my parameters for that form come in my controller like this:

params[:my_form][:my_param]

which means that it's not possible for me to do a param :my_param declaration. The only workaround is to use form_tag instead of form_for inside my view.

Thank you for your time

Unable to load application: NameError: uninitialized constant RailsParam::Param

Basic Info

  • rails_param Version: latest (7ef3018)
  • Ruby Version: ruby 2.6.5-p114
  • Rails Version: 4.2.11.1

Issue description

Latest code refactor from 3 days ago 7ef3018

Raised an error "Unable to load application: NameError: uninitialized constant RailsParam::Param" https://pastebin.pl/view/5f75a8ea

Steps to reproduce

Build rails_para using the latest code in the master branch.

Workaround

Build rails_para using commit: 8235f1b v0.11.1 or lower
8235f1b

param! :foo, ActionDispatch::Http::UploadedFile will throw an exception when nil

Basic Info

  • rails_param Version: 1.0.2
  • Ruby Version: 3.0.2
  • Rails Version: 6.1.4.1

Issue description

I have an endpoint that has the following param:

param! :foo, ActionDispatch::Http::UploadedFile

When sending foo: nil it will produce the following error:

'' is not a valid ActionDispatch::Http::UploadedFile

This was not a problem with 0.11.2 version of the rails_param gem.

Stack trace:

      "/Users/ak/.rvm/gems/ruby-3.0.2/gems/rails_param-1.0.2/lib/rails_param/param_evaluator.rb:82:in `rescue in coerce'",
      "/Users/ak/.rvm/gems/ruby-3.0.2/gems/rails_param-1.0.2/lib/rails_param/param_evaluator.rb:76:in `coerce'",
      "/Users/ak/.rvm/gems/ruby-3.0.2/gems/rails_param-1.0.2/lib/rails_param/param_evaluator.rb:17:in `param!'",
      "/Users/ak/.rvm/gems/ruby-3.0.2/gems/rails_param-1.0.2/lib/rails_param/param.rb:3:in `param!'",
      "/Users/ak/Projects/project/app/controllers/a_controller.rb:34:in `update'",

problem : setting default value and throwing errors case param

1 when param type is boolean but param value isn't boolean value. it will set param value to nil
I think it should throw error as same as other param type.

example

action controller receive `param[:test_boolean] = '123456'`
param! :test_boolean, :boolean
param[:test_boolean] # return nil

2 when param type is boolean and set default value is boolean

you code is options[:default].present? to check default presence
when default: boolean ? it's wrong.

example

param! :test_boolean, :boolean, default: false

options[:default].present? will return false
this param will not be set to false value

Friendly url issue

we have friendly ids like '41-hello', there is no way to convert and validate with rails_param.

InvalidParameterError does not contain "param" when coercion validation fails

Basic Info

  • rails_param Version: 1.3.0
  • Ruby Version: 3.2.2
  • Rails Version: 7.0.6

Issue description

param! :foo, Float

With value aa, this raises InvalidParameterError with the message 'aa' is not a valid Float. However, InvalidParameterError#param returns nil. The parameter name is lost here.

Quick fix : in RailsParam::ParamEvaluator#param!, when calling #coerce, pass the parameter_name as argument so that it could be set when raising InvalidParameterError.

Thanks

Parsing the date/time parameter depends on the local zone setting in the operating system, not in the Rails application

Basic Info

  • rails_param Version:
  • Ruby Version: 3.2.2
  • Rails Version: 7.1.1

Description

Using params! Time gives incorrect results in case of parameter parsing without specifying time zone.
In this case the result depends on the local zone setting on the running computer/docker, but should be determined by the time zone setting in the application configuration.

Steps for reproduction

For the same application with time zone settings:

  • run in docker with operation system time zone
  • run in docker with operation system without time zone

Rails console example

Rails Time zone is set, container time zone - different (not set)

Applications are different in this example, but it is not a key.

[4] pry(main)> param = '01.01.2023 00:00:00'
=> "01.01.2023 00:00:00"
[5] pry(main)> options = { format: '%e.%m.%Y %H:%M:%S'}
=> {:format=>"%e.%m.%Y %H:%M:%S"}
[6] pry(main)> type = Time
=> Time
[7] pry(main)> type.strptime(param, options[:format])
=> 2023-01-01 00:00:00 +0000
[8] pry(main)> "01.01.2023 00:00:00".in_time_zone
=> Sun, 01 Jan 2023 00:00:00.000000000 MSK +03:00
[9] pry(main)> Time.parse(param)
=> 2023-01-01 00:00:00 +0000
[10] pry(main)> Problems::Application.config.time_zone
=> "Europe/Moscow"

Rails Time zone is set, container time zone - the same

>> param = '01/01/2023 00:00'
=> "01/01/2023 00:00"
>> option = { format: '%e.%m.%Y %H:%M:%S'}
=> {:format=>"%e.%m.%Y %H:%M:%S"}
>> type = Time
=> Time
>> options = { format: '%e.%m.%Y %H:%M:%S'}
=> {:format=>"%e.%m.%Y %H:%M:%S"}
>> param = '01.01.2023 00:00:00'
=> "01.01.2023 00:00:00"
>> type.strptime(param, options[:format])
=> 2023-01-01 00:00:00 +0300
>> Souz::Application.config.time_zone
=> "Europe/Moscow"
>> param.in_time_zone
=> Sun, 01 Jan 2023 00:00:00.000000000 MSK +03:00

[Idea] Extract validation to external file

Basic Info

  • rails_param Version: 0.11.1
  • Ruby Version: 3.0.1
  • Rails Version: 6.1.1

Issue description

I've been leveraging rails_params in one of prior projects. It works great however I prefer to keep controller neat. I wrote a chuck of code to extract validation rules to external files under some path e.g /app/validators/.../*._validator.rb. Validation file itself could look like:

module Api
  module V1
    class SessionsValidator
      include RailsParam::Param

      attr_reader :params

      def initialize(params)
        @params = params
      end

      def create
        param! :username, String, required: true, blank: false
        param! :password, String, required: true, blank: false
      end

      def refresh
        param! :refresh_token, String, required: true, blank: false
      end
    end
  end
end

What do you think about such solution? If you find it as useful I could open a PR.

params with value was overwrite by default

Basic Info

  • rails_param Version: 0.10.2
  • Ruby Version: 2.3.8
  • Rails Version: 4.2.11

Issue description

param! :aa, String, required: true
param! :bb, String, required: false, default: lambda { params[:aa]}

I want to set params[:bb] to params[:aa] when params[:bb] was empty, but when I set :bb in request it was overwrite by lambda { params[:aa]}

Steps to reproduce

see Issue description

code

this code set value to default not check params[name] is empty.

module RailsParam
  module Param

        # set default
        if options[:default].respond_to?(:call)
          params[name] = options[:default].call
        elsif params[name].nil? && check_param_presence?(options[:default])
          params[name] = options[:default]
        end

  end
end

Nested parameters?

Is there a way to validate nested parameters?

Ex:

   params[:user][:id] 

Thank you!

I want to allow arrays of nullable integer types.

Thank you very much for allowing us to use rails_param!
I have one question.

As the title says, what should I do if I receive an array that accepts null as a parameter?

def validate_params
  param! :ids, Array, required: true do |item, id|
    item.param! id, Integer # I want to allow this to be null!
  end
end

Forgive my newbie question.

Basic Info

  • rails_param Version: 1.3.0
  • Ruby Version: 3.0.3
  • Rails Version: 7.0.3

New release?

I just stumbled across some Rails 5 compatibility issue and noticed that the code in question has already been fixed in the source code.

The last release is from August 2014, are there any plans to bundle the current state of the library into a new release?

Hash type validation

Basic Info

  • rails_param Version: 0.11.1
  • Ruby Version: 3.0.1
  • Rails Version: 6.1.3.1

Issue description

It seems like Hash type validation does not work as expected. Having the following:

       param! :receipt, Hash, required: true, blank: false do |receipt|
            receipt.param! :packageName, String, required: true, blank: false
            receipt.param! :productId, String, required: true, blank: false
            receipt.param! :purchaseToken, String, required: true, blank: false
       end
        let(:request_params) do
            {
              receipt: 'some-string'
            }
        end

I expect to receive a receipt attr value as a hash with nested attributes. On the other hand, instead of wrong type error the spec passes while the key value is just a string.

Could anyone reproduce that case and confirm whether the issue exists?

Thanks in advance.

automatically permit validated params

Basic Info

  • rails_param Version: 1.3.1
  • Ruby Version: 3.2.1
  • Rails Version: 7.0.x

Issue description

The param! methods does not call params.permit over validated parameters, this means that after the validation block we need to manually permit and extract only the required fields.
e.g.

 param! :reaction, Hash, required: true do |r|
      r.param! :note, String, required: false, blank: true
      r.param! :like, :boolean, required: false
      r.param! :love, :boolean, required: false
      r.param! :reject, :boolean, required: false
end

# or with a separate method if you prefer
reaction_params = params.permit(reaction: [:like, :love, :reject, :note])

This is very repetitive and error-prone when deleting/adding new fields and could lead to dangerous errors.

The README is not very clear about this, from a first read I understood that I could use this gem and forget about the params.permit but now I figured out it's not like that.

I propose to automatically permit params (and nested params) based on the fields declared in param! by overriding the params variable or using a new instance variable such as @sanitized_params, @rails_params or whatever you prefer.

I'd like to open a PR if you like this idea, otherwise I will just keep the fork for me.

What do you think?

Array items error message not comprehensible

Basic Info

  • rails_param Version: 1.1
  • Ruby Version: 2.6.6
  • Rails Version: 5.2.6

Issue description

When using Array validator, the error message is incomprehensible:

param! :status, Array do |array, index|
  array.param! index, String, in: %w[a b c]
end

The error message is Parameter 0 must be within [\"a\", \"b\", \"c\"]

I expect to receive, at least, something with an explicit context, like Parameter status[0] must be within [\"a\", \"b\", \"c\"].
Imagine that when I have several Array parameters to be validated, I can never know from which one the error comes...

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.