On Tuesday, 4 September 2012 06:27:52 UTC-5, Ruby-Forum.com User wrote:
>
> Yes,  I'm learning to program on my own...  I don't believe anyone would 
> pay for my work :-) 
>
> Thanks, you were right - it is writing to the file and I can see it 
> after closing. 
> Can I follow with one last question... 
>
> I have written a method, saved it in a table, and this is what I am 
> writing to the temp file. Can I require the file and then call the 
> method (getting the returned arguments)  from the temp file as it is 
> saved as a .rb file?  eg... 
>
> def format_q_gen 
>       file = Tempfile.new([generator_file_name, ".rb"], 
> "./lib/generators") 
>       file.write(question) 
>       returned_question = generator_file_name  # Calls the method in the 
> tempfile 
>       formatted = { 
>         question: q["question_1"], 
>         correct_answer_letter: "a" 
>          } 
>       file.close 
>       file.unlink 
>     end 
>

I would personally write that method to be a little safer IMO.  Yeah it's 
true that you can sometimes guarantee that problems won't happen but 
relying on that slim chance is bad, it's better to let file closing 
operations fall onto an ensure so that if something does go wrong then you 
can at least guarantee you aren't sloppy about it.

    def demo_tempfile
      file = Tempfile.new(["hello_world", ".rb"], "./lib/generators")
      file.write("$stdout.puts 'hello world'")
      file.rewind
      $stdout.puts file.read # Will output the source without evaling.
      # raise # Uncomment this line to see what I mean about ensure.
    ensure
      file.close!
    end
 

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msg/rubyonrails-talk/-/sXQZ1lknkrYJ.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to