logo
down
shadow

Check params presence in Grape


Check params presence in Grape

By : user2948528
Date : November 14 2020, 04:51 PM
it should still fix some issue Method doesn't work cause by default Grape provides even nil values in declared(params) hash. So if :color provided but :size is not, hash looks like {declared_params: {color: 'green', size: nil}}, which is not acceptable for Mongoid. All magic is hidden in include_missing option provided by declared. So assignment that option to false like Product.where declared(params, include_missing: false) will cut all nil values and Mongoid starts to accept declared hash.
code :


Share : facebook icon twitter icon
Grape API modify parameter presence error

Grape API modify parameter presence error


By : user6483486
Date : March 29 2020, 07:55 AM
wish of those help As you basically just want to re-structure the error, and not completely change the text, you can use a custom error formatter.
Example:
code :
require "grape"
require "json"

module MyErrorFormatter
  def self.call message, backtrace, options, env
      { :response_type => 'error', :response => message }.to_json
  end
end

class MyApp < Grape::API
  prefix      'api'
  version     'v1'
  format      :json

  error_formatter :json, MyErrorFormatter

  resource :thing do
    params do
      requires :province, :type => String
    end
    get do
      { :your_province => params[:province] }
    end
  end
end
curl http://127.0.0.1:8090/api/v1/thing?province=Cornwall
{"your_province":"Cornwall"}

curl http://127.0.0.1:8090/api/v1/thing
{"response_type":"error","response":"missing parameter: province"}
How to sanitize grape params

How to sanitize grape params


By : Jorge Cavaiuolo
Date : March 29 2020, 07:55 AM
I wish this help you In grape you need to declare your params before the actual method.
Within the method the params object is a Hashie::Mash instance, and does not have APIs like permit and sanitize...
code :
params do
  requires :id, type: Integer
  optional :text, type: String, regexp: /^[a-z]+$/
  group :media do
    requires :url
  end
  optional :audio do
    requires :format, type: Symbol, values: [:mp3, :wav, :aac, :ogg], default: :mp3
  end
  mutually_exclusive :media, :audio
end
put ':id' do
  # params[:id] is an Integer
end
raw_parameters = { :email => "john@example.com", :name => "John", :admin => true }
parameters = ActionController::Parameters.new(raw_parameters)
user = User.create(parameters.permit(:name, :email))
Grape: required params with grape-entity

Grape: required params with grape-entity


By : Morauer
Date : March 29 2020, 07:55 AM
I wish did fix the issue. After some work, I was able to make grape work as I think it should be working. Because I don't want to repeat the code for both of the validation and the documentation. You just have to add this to the initializers (if you are in rails, of course). I also was able to support nested associations. As you can see, the API code looks so simple and the swagger looks perfect. Here are the API and all the needed entities:
app/api/smart/entities/characteristics_params_entity.rb
code :
module Smart
  module Entities
    class CharacteristicsParamsEntity < Grape::Entity

      root :characteristics, :characteristic
      expose :id, documentation: { type: Integer, desc: 'Id of the characteristic' }

    end
  end
end
module Smart
  module Entities
    class CharacteristicsEntity < CharacteristicsParamsEntity

      expose :id, documentation: { type: Integer, desc: 'Id of the characteristic' }
      expose :name, documentation: { type: String, desc: 'Name of the characteristic' }
      expose :description, documentation: { type: String, desc: 'Description of the characteristic' }
      expose :characteristic_type, documentation: { type: String, desc: 'Type of the characteristic' }
      expose :updated_at, documentation: { type: Date, desc: 'Last updated time of the characteristic' }

    end
  end
end
module Smart
  module Entities
    class AppsParamsEntity < Grape::Entity

      expose :os, documentation: { type: String, desc: 'Operative system name', values: App::OS_LIST, required: true }
      expose :characteristic_ids, using: CharacteristicsParamsEntity, documentation: { type: CharacteristicsParamsEntity, desc: 'List of characteristic_id that the customer has', is_array: true }


    end
  end
end
module Smart
  module Entities
    class AppsEntity < AppsParamsEntity

      unexpose :characteristic_ids
      expose :id, documentation: { type: 'integer', desc: 'Id of the created app', required: true }
      expose :customer_id, documentation: { type: 'integer', desc: 'Id of the customer', required: true }
      expose :characteristics, using: CharacteristicsEntity, documentation: { is_array: true, desc: 'List of characteristics that the customer has' }

    end
  end
end
module Smart
  module Version1
    class Apps < Version1::BaseAPI

    resource :apps do

        # POST /apps
        desc 'Creates a new app' do
          detail 'It is used to register a new app on the server and get the app_id'
          params Entities::AppsParamsEntity.documentation
          success Entities::AppsEntity
          failure [[400, 'Bad Request', Entities::ErrorEntity]]
          named 'create app'
        end
        post do
          app = ::App.create! params
          present app, with: Entities::AppsEntity
        end

      end

    end
  end
end
class Evaluator
  def initialize(instance)
    @instance = instance
  end

  def params parameters
    evaluator = self
    @instance.normal_params do
      evaluator.list_parameters(parameters, self)
    end
  end

  def method_missing(name, *args, &block)
  end

  def list_parameters(parameters, grape)
    evaluator = self
    parameters.each do |name, description|
      description_filtered = description.reject { |k| [:required, :is_array].include?(k) }
      if description.present? && description[:required]
        if description[:type] < Grape::Entity
          grape.requires name, description_filtered.merge(type: Array) do
            evaluator.list_parameters description[:type].documentation, self
          end
        else
          grape.requires name, description_filtered
        end
      else
        if description[:type] < Grape::Entity
          grape.optional name, description_filtered.merge(type: Array) do
            evaluator.list_parameters description[:type].documentation, self
          end
        else
          grape.optional name, description_filtered
        end
      end
    end
  end
end

module GrapeExtension
  def desc name, options = {}, &block
    Evaluator.new(self).instance_eval &block if block
    super name, options do
      def params *args
      end

      instance_eval &block if block
    end
  end
end

class Grape::API
  class << self
    prepend GrapeExtension
  end
end
Check Presence of multiple params

Check Presence of multiple params


By : Martoch
Date : March 29 2020, 07:55 AM
To fix this issue I need to check the presence of multiple params. Currently what i have written is , You can use the Enumerable.all? method:
code :
%i( p1 p2 p3 ).all? { |key| params[key].present? }
params.values_at(*%i( p1 p2 p3 )).all?(&:present?)
params.values_at(:p1, :p2, :p3).all?(&:present?)
How to check for parameter presence: params.require(:data) or params[:data].present? and why

How to check for parameter presence: params.require(:data) or params[:data].present? and why


By : nilesh sinha
Date : March 29 2020, 07:55 AM
should help you out It seems to me that you may have a slight misunderstanding in the purpose of params.require.
If your aim is to simply check for the existance of a certain parameter to organise the flow of code, then yes always use .present?
Related Posts Related Posts :
  • How do I get ruby-prof to ignore Ruby core / standard library / gem methods?
  • How do I give my instance variable a getter?
  • syntax error, unexpected '=', expecting keyword_end
  • Symbol literal or a method
  • Singleton logger usage in ruby
  • Difficult code packaging design
  • Passing absent parameters
  • Is there a more efficient way of ensuring my database gets closed?
  • Take in escaped input in Ruby command line app
  • String with comma-separated values and newlines: split values and create arrays for each newline
  • Instance variables on Ruby main class
  • How do I cache user specific objects
  • How to specify the location of the chromedriver binary
  • How to setup "application/ld+json" schema.org meta data in rails 4 app
  • How to use String split[]
  • Capture Ruby Logger output for testing
  • Regex group match if present
  • Unusual use of module namespacing
  • Why doesn't this loop stop?
  • How do I run Rails/Rake from another directory?
  • Ruby Tempfile doesn't Create File on Disk
  • Consecutive letter frequency
  • Calling second-level function from the second level in Ruby
  • How do I use a Chef Resource in a Library
  • Ruby Method Name Interpolation
  • Weird behavior of #upcase! in Ruby
  • Ruby array access position in array
  • Ruby NameError: Undefined local variable
  • Using Nokogiri to validate XML: finding the line-nr of validation errors?
  • How to calling a function with arguments in one .rb script to another .rb script
  • Get and clear cookie using rest-client
  • invalid argument creating a ruby dev env with docker & fig
  • How can I better test equality for decorated objects?
  • Replace text in brackets gsub
  • Ruby's Array Combination Method
  • Don't have access to Heroku app
  • Take any hash keys and flatten into mixed array
  • Ruby On Rails Relationship Between Model, View, And Controller
  • Quitting method chain execution early
  • Data scrapping with Nokokiri and Pismo
  • Date format ends before converting entire input string
  • Rails 4: display values for lookups
  • Search for uppercased substring
  • How to create a method that checks if string1 can be rearranged to equal string2?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org