How to convert a Ruby object to JSON from a File? [duplicate] - ruby

This question already has answers here:
How to convert a Ruby object to JSON
(3 answers)
Closed 8 years ago.
I'm trying to use the Linguist gem: https://github.com/github/linguist
My code is:
require 'linguist'
filePath = ARGV
langDetails = Linguist::FileBlob.new(filePath)
puts langDetails
That outputs: #<Linguist::FileBlob:0x007faf93b17200>
However, when I do puts langDetails.language, I get
/Users/myuser/.rvm/gems/ruby-1.9.3-p545#linguist/gems/github-linguist-2.10.15/lib/linguist/file_blob.rb:39:in `stat': can't convert Array into String (TypeError)
from /Users/myuser/.rvm/gems/ruby-1.9.3-p545#linguist/gems/github-linguist-2.10.15/lib/linguist/file_blob.rb:39:in `mode'
from /Users/myuser/.rvm/gems/ruby-1.9.3-p545#linguist/gems/github-linguist-2.10.15/lib/linguist/blob_helper.rb:294:in `language'
from ./linguist.rb:9:in `<main>'
I'm not entirely sure what I'm doing wrong. Ideally I want the data back as a JSON object. How do I accomplish this?

Look at the source. FileBlog is saying File.stat(#path).mode.to_s(8) but #path is an array. filePath needs to be a path string, but ARGV is an array.
Perhaps you meant ARGV[0]?

Related

Ruby: Add line in file [duplicate]

This question already has answers here:
What are the Ruby File.open modes and options?
(2 answers)
Closed 6 years ago.
I have a file in which one I want to store some datas.
Using IRB, I can add different lines in the file. However, using a Ruby script writen in a file, I have issues.
I can write a line, it is stored as it should be, but when I re launch the script and re use the method, it overwrites what was in the file instead of adding content at the next line.
def create_new_account
puts "Set the account's name"
#account_name = gets
puts "New account's name: #{#account_name}
open("accounts.txt","w+") do |account_file|
account_file.write "ac;#{#account_name}\n"
end
end
I had a look to the different parameters of the method open, but seems like it's not there.
Moreover, I tried puts instead of write, but there is no difference, always the same problem.
Could someone help me understand what is wrong with the code?
Thanks
Try opening the file in append mode like so
open('accounts.txt', 'a+')
otherwise the file is opened so as to overwrite the existing data.
"a" - Write-only, each write call appends data at end of file.
Creates a new file for writing if file does not exist.

Using `gets` for file path [duplicate]

This question already has answers here:
Ruby: String Comparison Issues
(5 answers)
Closed 3 years ago.
I'm writing a script to edit an excel file. I'm testing if it collects information from a user.
require 'rubygems'
require 'win32ole'
print "filpath?"
$filepath = $stdin.gets
print "sheet?"
$sheetname = $stdin.gets
excel = WIN32OLE.new('Excel.Application')
excel.visible = true
workbook = excel.workbooks.Open($filepath)
worksheet = workbook.Worksheets($sheetname)
worksheet.Cells(2,2).Value = 10
workbook.saved = true
workbook.Save
excel.ActiveWorkbook.Close(0)
excel.Quit()
When I put my file path in the script directly, it works fine. It can look up the excel file and edit it normally. However, when I collect it from a gets statement, it gives me this error message:
test.rb:20:in `method_missing': (in OLE method `Open': ) (WIN32OLERuntimeError)
OLE error code:800A03EC in Microsoft Excel
Sorry, we couldn't find C:\filename.xlsx
. Is it possible it was moved, renamed or deleted?
HRESULT error code:0x80020009
Exception occurred.
from test.rb:20:in `<main>'
Not sure what is happening. I would love any help.
The end line character is appended to the file name when you receive it with gets, but probably your file is not named as such. Add .chomp after gets. It is also better to check the existence and the accessibility of the file before passing it to win32ole.

ruby open pathname with specified encoding

I am trying to open files telling Ruby 1.9.3 to treat them as UTF-8 encoding.
require 'pathname'
Pathname.glob("/Users/Wes/Desktop/uf2/*.ics").each { |f|
puts f.read(["encoding:UTF-8"])
}
The class documentation goes through several levels of indirection, so I am not sure I am specifying the encoding properly. When I try it, however, I get this error message
ICS_scanner_strucdoc.rb:4:in read': can't convert Array into Integer (TypeError)
from ICS_scanner_strucdoc.rb:4:inread'
from ICS_scanner_strucdoc.rb:4:in block in <main>'
from ICS_scanner_strucdoc.rb:3:ineach'
from ICS_scanner_strucdoc.rb:3:in `'
This error message leads me to believe that read is trying to interpret the open_args as the optional leading argument, which would be the length of the read.
If I put the optional parameters in, as in puts f.read(100000, 0, ["encoding:UTF-8"]) I get an error message that says there are too many arguments.
What is the appropriate way to specify only the encoding? Would it be correct to say that this is an inconsistency between the documentation and the behavior of the class?
Mac OS 10.8
rvm current reports "ruby-1.9.3-p484"
I'm not sure you want to specify encoding for path name or for file itself.
If it is latter, this maybe what you want.
Pathname.glob("/Users/Wes/Desktop/uf2/*.ics").each { |f|
puts File.open(f,"r:UTF-8")
}
With Pathname.read you can write like this.
Pathname.glob("/Users/Wes/Desktop/uf2/*.ics").each do |f|
path = Pathname(f)
puts path.read
end

how to convert data URI to file in Ruby

How do I convert a data URI that comes from the result of the FileReader API into an image file that can be saved in the file system in Ruby?
What I'm currently trying to do is using base64 decode to convert the data_uri string which looks like this: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgA... into base 64 encoded string because according to this stackoverflow answer I need to replace all the instances of spaces into +. The answer is in PHP but I'm currently working on Ruby and Sinatra so I'm not sure if it still applies, but when using the equivalent code:
src = data_uri.gsub! ' ', '+'
src = Base64.decode64(src)
f = File.new('uploads/' + 'sample.png', "w")
f.write(src)
f.close
I get the following error:
undefined method `unpack' for nil:NilClass
What I'm trying to achieve here is to be able to convert the data URI to a file.
There's no need to reinvent the wheel. Use the data_uri gem.
require 'data_uri'
uri = URI::Data.new('data:image/gif;base64,...')
File.write('uploads/file.jpg', uri.data)

Ruby block to string instead of executing [duplicate]

This question already has answers here:
Printing the source code of a Ruby block
(6 answers)
Closed 8 years ago.
Take this example:
write_as_string { puts 'x' }
I then want to be able to do
def write_as_string(&block)
puts block.to_s
end
When I execute this, I want the output to be:
"puts 'x'"
I want to be able to receive the block and get the actual code for the block instead of executing it.
Motivation: Creating a DSL, I want to the mock to be converted into a number of other method calls, hidden from the calling code - using existing objects and methods without monkey patching them.
Any ideas on this would be great!
Thanks
Ben
If you're on Ruby 1.9, you can use the sourcify gem. It provides Proc#to_source, which is like ParseTree's Proc#to_ruby.
When using sourcify, if you have nested procs in your source code, you might have to help it along with the :attached_to option:
## (Works in Ruby 1.8) Using ParseTree (with parse_tree_extensions)
block.to_ruby
## (Works in Ruby 1.9) Using sourcify
block.to_source
## Try this if you get Sourcify::NoMatchingProcError or Sourcify::MultipleMatchingProcsPerLineError
block.to_source :attached_to => :name_of_block_in_source_code
I posted about ParseTree and Ruby 1.9 in my company's blog.
Duplicate: Printing the source code of a Ruby block
sudo gem install ParseTree
sudo gem install ruby2ruby
then
require 'rubygems'
require 'parse_tree'
require 'parse_tree_extensions'
require 'ruby2ruby'
def block_as_string &block
block.to_ruby
end
results in
irb(main):008:0> block_as_string {puts 'x'}
=> "proc { puts(\"x\") }"
You want the ruby2ruby gem, which does this nicely. Unfortunately, to analyze a block this gem depends on ParseTree, which is unsupported in Ruby 1.9.

Resources