Generate params hash for Model


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. class Object
  2.  
  3. # provides a params hash which will can useful for testing
  4. # USAGE : Model.to_params :name_of_params_hash # => :name_of_params_hash defaults to :params
  5. # to override the params hash, just pass a hash list of attributes :
  6. # Model.to_params.merge(:my_options => "my_value")
  7. def to_params(params_name="params")
  8. @@params_var = params_name.to_sym
  9. attributes = self.new.attributes.keys.map {|c| c.to_sym}
  10. p_hsh = {}
  11. attributes.map {|a| p_hsh[a]=nil}
  12. params = {@@params_var => p_hsh}
  13.  
  14. params.instance_eval do
  15. #overrides Hash#merge method by merging just the sub hash and not the main one
  16. def merge(options={})
  17. self[@@params_var].update(options)
  18. return self
  19. end
  20. end
  21. return params
  22. end
  23.  
  24. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.