7

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
user938363
  • 9,990
  • 38
  • 137
  • 303
  • 2
    Can you show an example, how you can create a hash and **not** call that method in the process? – Sergio Tulentsev Jun 04 '13 at 21:05
  • 3
    If you use `eval()`, **make sure there is not user's input in the hash** you are trying to eval. Imagine a user posts a hash like this: `{ :a => User.delete_all }`! – MrYoshiji Jun 04 '13 at 21:06
  • What is the use case for this? Where do you get your string from? IMHO it is not a good idea to do this. There must be a better way to inputing the data in a safer way – Tilo Jun 04 '13 at 21:08
  • the string is from data table and hash is used to compose form on .html.erb – user938363 Jun 04 '13 at 21:39
  • I think this should be re-opened because the question has been restaged as without eval. I want to turn a free text value into a hash, and of course eval is not an option. – baash05 May 15 '14 at 06:23
  • user938363, could you delete this question? I've re-asked it in the hopes the answer is less EVALish. I don't want it flagged as a duplicate. – baash05 Oct 20 '14 at 01:45

1 Answers1

9

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).

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • There is further processing of the hash input and use it for composing form on .html.erb. So if the eval kicks in for the method during string=>hash conversion, then we are going to have syntax error from rails. – user938363 Jun 04 '13 at 21:26
  • <%= simple_form_for model, :method => :put, :url => search_results_url do |f| %> <%= fields_details.each do |field, layouts| %> <%= f.input field, layouts %> <% end %> <% end %> – user938363 Jun 05 '13 at 04:00