Here’s a sample of the code, which I’m trying to load from rails c (inside the lib folder–the file data2.json is also inside of the lib directory)
$LOAD_PATH.unshift(File.expand_path(".", File.dirname(__FILE__)))
$LOAD_PATH.unshift(File.expand_path("./lib", File.dirname(__FILE__)))
require 'company_gem_class'
class LoadJson
def go
File.open(Rails.root, 'lib', 'file.json') do |f|
f.each_line do |line|
this_line = JSON.parse(line)
hash_parser = CompanyGemClass.new(line)
c = Company.new
c.followers = hash_parser.followers
c.company_name = hash_parser.company_name
c.date_joined = hash_parser.date_joined
...
c.save
end
end
...
end
The plan was/is to load all this raw data through a single (Company) class directly from the rails console. I’ve been getting lots of “json file does not exist” (Ennooent::path/to/file.json does not exist).
I’ve tried putting it in the lib/assets folder and lib folders, but no success yet. How might I go about this task of mass-uploading these json–>ruby objects to the db?
^^I’ve already bundle-installed the json gem.
^^The json files are one hash per line, so that’s why I did it like this
I’m sure you know (however it was not completely obvious from your question) that
File.opendoes not useLOAD_PATHfor anything. So no matter what you put inLOAD_PATH, it will not affect howFile.openworks.LOAD_PATHonly modifies howrequiresearches for files.In Rails all your file operations should use
Rails.rootas the base path. You cannot rely on your current working directory to be something specific when working with Rails.So any
LOAD_PATHmodifications should be done with something like this:Because of (1) and (2) – If you’re going to open any file with
File.openthe most reliable way to do it is usingRails.root:Or in your case:
In Rails
libis already in yourLOAD_PATHby default. So you do not need to add it separately.