Ruby right write
-
If reading a file is defined
def load_json(file) subDir = "nset/Sketchup/" path = File.join(File.dirname(__FILE__), subDir, file) json = IO.read(File.join(File.dirname(__FILE__), subDir, file)) end
how to define write?
Thanks
Chris
-
hmm..
I never use the IO class directly to read/write files.I use the File class's methods.
# Read Files f = File.open(file, 'rb') # read from file f.close
# Write Files f = File.open(file, 'w') f.puts 'hello world' f.close
-
Thanks Thom. Actually Jim wrote that and he should be asleep. I don't understand
(File.join(File.dirname(__FILE__), subDir, file))
- why it has to be joined. Do I need to know. Is it relevant to writing?Thanks
Chris
-
The join method ensures that when you combine parts of a filename that it's compiled correctly, with forward slashes etc /. It return a fully compiled path to your file.
-
Thanks again
-
One other thing has come from this. I can write to the same file using Ruby or activeXObject in an .hta. The Ruby version adds an extra empty line which throws an "unterminated string constant" error when read. Any idea about what is going on?
Thanks
function coreRubyReq(callback, params) { window.location = "skp;" + callback + "@" + params.join(';'); } function coreJsonSave(fileName, json) { var ForWriting, objFSO, objFile, txt; txt = JSON.stringify(json); if(config.SU === 1){ coreRubyReq('save_json', [fileName, txt]); } else{ ForWriting = 2; objFSO = new ActiveXObject("Scripting.FileSystemObject"); objFile = objFSO.CreateTextFile(fileName, ForWriting); objFile.Write( txt ); objFile.Close(); } }
@dlg.add_action_callback("save_json") { |d, a| p = a.split(";") subDir = "nset/Sketchup/" file = File.join(File.dirname(__FILE__), subDir, p[0]) f = File.open(file, 'w') f.puts p[1].to_s f.close }
-
hmm...
extra line? at the end? or for each line?
Could be that my example opened the file as binary.
#binary read f = File.open(file, 'rb')
#normal read f = File.open(file, 'r')
This the latter treats line breaks differently. (linebreaks are different from platform to platform)
-
I left Jim's for the read and used yours for the write.
-
Maybe if I pass it though a hidden input?? I should do that anyway - forgot!
-
? to get rid of extra lines?
-
@chrisglasier said:
> @dlg.add_action_callback("save_json") { |d, a| > p = a.split(";") > subDir = "nset/Sketchup/" > file = File.join(File.dirname(__FILE__), subDir, p[0]) > f = File.open(file, 'w') > f.puts p[1].to_s > f.close > } >
I think the problem is
f.puts p[1].to_s
Try using
f.write p[1].to_s
-
Works ... thanks Chris
Chris
-
I think it's odd that the parser would be sensitive to a newline at the end of the file.
Advertisement