Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-plugins

Shorthand for accessing values from params hash


I often feel the need to access the individual key-value pairs from the 'params' hash, as if they were local variables.

I find that using local variables instead of writing 'params' every time, makes my code easier to understand.

So instead of using the values like params[:first_variable] I would do something like :

first_var  = params[:first_variable]

second_var = params[:second_variable]
... 

and in my program i would use this short notation instead of writing params[:first_var] every time.

The problem with this is that the size of my functions can grow significantly, when I have many values in params.

Is there a better way to reference the objects from 'params' as local variables in my function ?


Solution

  • You could redefine method_missing in which class you want this functionality. If you do, remember the cardinal rules of method_missing - if you can't handle it, call pass it on (to super); and update respond_to? in parallel.

    Something like this, perhaps.

    class Foo
      def method_missing(name, *args, &block)
        if params.include? name
          params[:name]
        else
          super
        end
      end
    
      def respond_to?(name)
        if params.include? name
          true
        else
          super
        end
      end
    end
    

    Remember that Rails makes heavy use of method_missing already, so either only redefine it on your own classes, or alias the existing version and call that instead of super when you aren't handling.