1. Instantize Keys in Rails

    29 September 2008

    If you find yourself doing something similar to this quite often:


    @name = parms[:organization][:name]
    @url = params[:organization][:url]

    You can save yourself a lot of time with this method:

    application.rb

    private
    def instantize_keys(hash)
    hash.each { |key, value| eval("@#{key} = #{value}") }
    end

    Now just call this private method in your controller method and pass the appropriate hash.

    instantize_keys(params[:organization])

    And now you have access to @name and @url

    On a side note: If you do find yourself using a lot of instance variable then you should re-evaluate your design philosophy.

Notes

  1. bcardarella posted this