Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to a hash in Ruby on Rails without using eval? [duplicate]

Here is the string which needs to convert into a hash.

"{:status => {:label => 'Status', :collection => return_misc_definitions('project_status') } }"

We can not use eval because eval will execute the method return_misc_definitions('project_status') in the string. Is there pure string operation to accomplish this conversion in Ruby/Rails?

like image 507
user938363 Avatar asked Jun 04 '13 20:06

user938363


1 Answers

As mentioned earlier, you should use eval. Your point about eval executing return_misc_definitions doesn't make sense. It will be executed either way.

h1 = {:status => {:label => 'Status', :collection => return_misc_definitions('project_status') } }
# or 
h2 = eval("{:status => {:label => 'Status', :collection => return_misc_definitions('project_status') } }")

There's no functional difference between these two lines, they produce exactly the same result.

h1 == h2 # => true

Of course, if you can, don't use string represenstation of ruby hashes. Use JSON or YAML. They're much safer (don't require eval).

like image 98
Sergio Tulentsev Avatar answered Sep 19 '22 23:09

Sergio Tulentsev