我正在尝试将在表单/调查中提交的响应存储到JSON文件中。目前,我的JSON文件返回null。我在弄清楚如何将表单上的响应保存到JSON文件时遇到麻烦。
require 'json'
class Survey
attr_reader :nationality, :employed, :income, :email
def initialize(args={})
@nationality = args["nationality"]
@employed = args["employed"]
@income = args ["income"]
@email =args ["email"]
end
def save
json = {
email: @email,
nationality: @nationality,
employed: @employed,
income: @income
}.to_json
open('answers.json', 'a') do |file|
file.puts json
end
end
end
require 'rack'
require_relative 'route'
require_relative 'template'
require_relative 'admin'
require_relative 'survey'
class App
def call(env)
response_headers = {}
request_cookies = Rack::Utils.parse_cookies(env)
route = Route.new(env)
status = route.name =~ /^\d\d\d$/ ? route.name.to_i : 200
template = Template.new(route.name, visit_count: request_cookies["session_count"].to_i+1)
[status, response_headers, [template.render]]
end
survey = Survey.new ''
survey
survey.save
end
require 'sinatra/base'
require 'rack'
require 'erb'
require_relative 'route'
class Admin < Sinatra::Base
use Rack::Auth::Basic, "Protected Area" do |username, password|
username == 'minhaj' && password == 'minhaj'
end
get '/' do
"<div>hi for some reason I don't need to put this in a string #{5+5}</div>
<p>
</div>hello</div>
</p>
"
end
end
class Route
ROUTES = {
"GET" => {
"/" => :home,
"/admin" => :admin,
"/authentication" => :authentication,
},
"POST" => {
"/check" => :check
}
}
attr_accessor :name
def initialize(env)
path = env["PATH_INFO"]
http_method = env["REQUEST_METHOD"]
@name = (ROUTES[http_method] && ROUTES[http_method][path]) || :not_found
end
end
#! usr/bin/env ruby
require 'rack'
load 'admin.rb'
load 'visit_counter.rb'
load 'app.rb'
require File.expand_path '../admin.rb', __FILE__
use Rack::Static, :urls => ['/stylesheet/style.css'], :root => 'public'
run Admin.new
run App.new
use VisitCounter
run Rack::URLMap.new({ "/admin" => Admin.new, "/" => App.new })
到目前为止,这是它的外观,正如我在运行应用程序时所提到的那样,我的Answers.json返回
{"email":null,"nationality":null,"employed":null,"income":null}
而不是返回在我的表单页面上提交的值。
答案 0 :(得分:0)
也许您可以尝试以下操作:
file = File.open(File.dirname(__FILE__) + '/answers.json', 'a+')
file.write json
file.write "\n"
file.close
请确保实际上首先填充了json
,您可以通过puts json
进行检查,或者如果您使用的是红宝石,则可以在调试模式下运行并在其上放置一个断点。
此外,您不能只是将代码放在类中并期望其被执行。
移动:
survey = Survey.new ''
survey.save
插入一个方法并专门调用它,或将其包括在call方法中。
让我知道它是否有效