app/controllers/new_controller.rb:
class NewController < ApplicationController
def enter_time
session[:dr] = 'dr'
if !params[:time].nil? then
Time.zone = #franchise.time_zone
inanhour = 1.hour.since(Time.zone.now)
delivery_time = delivery_time_format(params[:time])
delivery_time = delivery_time.change(offset: (Time.zone.now.utc_offset / 3600).to_s)
session[:target_time] = [delivery_time, inanhour].max.to_s
end
end
end
spec/controllers/new_controller_spec.rb:
require 'spec_helper'
describe NewController, :type => :controller do
before do
allow(controller).to receive(:current_user) { nil }
end
describe "POST /enter_time" do
let(:addr_str) { '2810 Derby St, Berkeley, CA, United States' }
let(:delivery_time) { '06/06/2015 12:15 PM' }
it "sets current time of time zone" do
address = VCR.use_cassette('retrieve_address #{addr_str}', record: :new_episodes) do
Address.retrieve_address(addr_str)
end
a = { id: address.id, text: addr_str, lat: address.lat, lng: address.lng, src: :text }
post :enter_time, { time: delivery_time }
expect(assigns(session['dr'])).to eq("dr")
end
end
end
throws the error:
expected: "dr" got: nil
neither expect(assigns(session['dr'])).to eq("dr") nor expect(assigns(session[:dr])).to eq("dr") works
Try: expect(session['dr']).to eq("dr").
session values are separate from assigns.
Related
I need to add a parameter to existing space and keep the existing data.
space is created like this:
function create_user()
local space = box.schema.create_space('user', { engine = 'memtx' })
space:format({
{ name = 'user_id', type = 'unsigned' },
{ name = 'name', type = 'string' },
{ name = 'is_active', type = 'boolean' },
})
space:create_index('users_id', { type = 'TREE', parts = { 'user_id', 'name' } })
end
i need to add the following parameters
{ name = 'is_online', type = 'boolean' }
{ name = 'session_id', type = 'unsigned', is_nullable = true }
how to write the required migration script?
it's my solution
function migrate_users()
local counter = 0
local space = box.space.users
space:format({})
for _, tuple in space:pairs(
nil, {iterator=box.index.ALL}
) do
local user_tuple = tuple:totable()
user_tuple[4] = nil
user_tuple[5] = false
space:replace(user_tuple)
counter = counter + 1
if counter % 10000 == 0 then
fiber.sleep(0)
end
end
space:format({
{ name = 'user_id', type = 'unsigned' },
{ name = 'name', type = 'string' },
{ name = 'is_active', type = 'boolean' },
{ name = 'session_id', type = 'unsigned', is_nullable = true },
{ name = 'is_online', type = 'boolean' }
})
space:create_index('session_id', { type = 'TREE', unique = false, parts = { 'session_id' } })
end
it is better to use spacer immediately
https://github.com/igorcoding/tarantool-spacer
I have an application in Vuejs, and a function that downloads questionnaire via graphQL. Function works perfect until I add variables to the query.
The working code of function is:
downloadQuestionnaire() {
console.log("downloadQuestionnaire: " + questionnaireVersion);
this.$apollo
.query({
query: gql`
query questionnaire {
questionnaire(inputParams: { language: "en", version: 1 }) {
sections {
section
cssClass
remainingItemsType
endingMessageText
questions {
qId
label
question
inputType
possibleAnswers {
paId
text
}
multipleAnswersAccepted
individualFormat
answers
}
}
}
}
`,
client: "questionnaire",
variables: {
version: questionnaireVersion
}
})
.then(data => {
// this.sections = data.questionnaire;
// console.log(data);
this.copyQuestionnaie(data.data.questionnaire.sections);
// console.log(JSON.stringify(data.data.questionnaire.sections));
})
.catch(error => {
this.error = error;
alert("E " + error);
});
},
and I need to parametrise the version in the the query, by changing it to:
downloadQuestionnaire() {
console.log("downloadQuestionnaire: " + questionnaireVersion);
this.$apollo
.query({
query: gql`
query questionnaire($version: Int) {
questionnaire(
inputParams: { language: "en", version: $version }
) {
sections {
section
cssClass
remainingItemsType
endingMessageText
questions {
qId
label
question
inputType
possibleAnswers {
paId
text
}
multipleAnswersAccepted
individualFormat
answers
}
}
}
}
`,
client: "questionnaire",
variables: {
version: 1
}
})
.then(data => {
// this.sections = data.questionnaire;
// console.log(data);
this.copyQuestionnaie(data.data.questionnaire.sections);
// console.log(JSON.stringify(data.data.questionnaire.sections));
})
.catch(error => {
this.error = error;
alert("E " + error);
console.log("ERROR: " + error);
});
},
And then I get the error:
RROR: Error: Network error: Response not successful: Received status code 400
I was trying to use the same syntax as in example here.
Am I injecting the parameters in a wrong way or I oversee some typo?
Update:
Below is the schema python code for the backend:
import graphene
from .db import get_questionnaire_in_dict, getAnswers, putAnswers
class InputParam(graphene.InputObjectType): # type: ignore
"""Input parameters for questionnaire."""
language = graphene.String(required=True)
version = graphene.Int(required=True)
class PossibleAnswer(graphene.ObjectType): # type: ignore
"""Possible answers pair of key and text."""
paId = graphene.String(description="Answer id")
text = graphene.String(description="Answer text")
def __init__(self, paId: str, text: str) -> None:
self.paId = paId
self.text = text
def display(self) -> None:
"""Print self content."""
print("Label: {label},\nQuestion: {question}".format(
label=self.label, question=self.question))
class Question(graphene.ObjectType): # type: ignore
"""Question object."""
qId = graphene.String()
label = graphene.String(description="Translated question label")
question = graphene.String(description="Translated question")
# qPointer = graphene.Field(QuestionItems)
multipleAnswersAccepted = graphene.Boolean()
possibleAnswers = graphene.List(PossibleAnswer)
answers = graphene.List(graphene.String)
inputType = graphene.String(description="HTML input type")
individualFormat = graphene.String()
def __init__(self, questionObj):
self.qId = questionObj["qPointer"]
self.label = questionObj["label"]
self.question = questionObj["question"]
self.inputType = questionObj["inputType"]
self.multipleAnswersAccepted = questionObj["multipleAnswersAccepted"]
if "individualFormat" in questionObj:
self.individualFormat = questionObj["individualFormat"]
else:
self.individualFormat = None
if questionObj["possibleAnswersPointer"]:
self.possibleAnswers = []
for key, value in enumerate(questionObj["possibleAnswersPointer"]):
possibleAnswer = PossibleAnswer(key, value)
self.addPossibleAnswer(possibleAnswer)
else:
self.possibleAnswers = None
self.answers = []
def display(self):
print("Question {inputType}".format(inputType=self.inputType))
self.qPointer.display()
def addPossibleAnswer(self, possibleAnswer):
self.possibleAnswers.append(possibleAnswer)
class Section(graphene.ObjectType):
section = graphene.String()
css_class = graphene.String()
remainingItemsCount = graphene.Int
remainingItemsType = graphene.String()
endingMessageText = graphene.String()
questions = graphene.List(graphene.NonNull(Question))
def __init__(self, sectionObj):
self.section = sectionObj["section"]
self.css_class = sectionObj["class"]
self.remainingItemsCount = sectionObj["remainingItemsCount"]
self.remainingItemsType = sectionObj["remainingItemsType"]
self.endingMessageText = sectionObj["endingMessageText"]
self.questions = []
def display(self):
print("Section {section}, class: {css_class}".format(
section=self.section, css_class=self.css_class))
def addQuestion(self, question):
self.questions.append(question)
class Questionnaire(graphene.ObjectType): # type: ignore
lang = graphene.String()
sections = graphene.List(Section)
def __init__(self, lang):
self.lang = lang.language
self.sections = []
def addSection(self, section):
self.sections.append(section)
class AnswersInputParam(graphene.InputObjectType): # type: ignore
userId = graphene.String(required=True)
version = graphene.Int(required=True)
class Answer(graphene.ObjectType): # type: ignore
qId = graphene.String()
answers = graphene.List(graphene.String)
def __init__(self, answerObj):
print("Answer creator: {}".format(answerObj))
self.qId = answerObj["qId"]
self.answers = answerObj["answers"]
class Answers(graphene.ObjectType): # type: ignore
userId = graphene.String()
version = graphene.Int()
answers = graphene.List(Answer)
def __init__(self, answersObj, userId, version):
self.userId = userId
self.version = version
self.answers = []
# print("answersObj[\"answers\"]: {}".format(answersObj))
for index, value in enumerate(answersObj):
print("_XXX_: {idx}={val}".format(idx=index, val=value))
answer = Answer(value)
self.addAnswer(answer)
def addAnswer(self, answer):
self.answers.append(answer)
class SaveAnswers(graphene.Mutation):
class Arguments:
userId = graphene.String(required=True)
version = graphene.Int(required=True)
answers = graphene.JSONString(required=True)
Output = Answers
def mutate(self, info, answers, version, userId):
putAnswers(userId, version, answers)
return Answers(answers, userId, version)
class Mutation(graphene.ObjectType):
save_answers = SaveAnswers.Field()
class Query(graphene.ObjectType):
answers = graphene.Field(
Answers, inputParams=AnswersInputParam(required=True))
def resolve_answers(self, info, inputParams):
answers = getAnswers(inputParams.userId, inputParams.version)
return Answers(answers, inputParams.userId, inputParams.version)
questionnaire = graphene.Field(
Questionnaire, inputParams=InputParam(required=True))
def resolve_questionnaire(self, info, inputParams):
qest = Questionnaire(inputParams)
_struct = get_questionnaire_in_dict(
inputParams.language, inputParams.version)
for _sectionRef, sectionData in _struct.items():
s = Section(sectionObj=sectionData)
# s.display()
for key, value in sectionData.items():
# print(key, value)
if key == "questions":
for _questionNum, questionData in enumerate(value):
q = Question(questionObj=questionData)
# q.display()
s.addQuestion(question=q)
qest.addSection(s)
return qest
schema1 = graphene.Schema(query=Query, mutation=Mutation)
# sample calls
# mutation{
# saveAnswers
# (
# userId: "U123",
# version: 1,
# answers: "[{\"qId\":\"s1q4\",\"answers\":\"0\"},{\"qId\":\"s2q1\",\"answers\":\"1\"},{\"qId\":\"s2q10\",\"answers\":[\"1\",\"3\"]}]"
# ) {
# userId
# version
# answers {
# qId
# answers
# }
# }
# }
# {
# answers(inputParams: {userId: "U123", version: 1})
# {
# answers{
# qId
# answers
# }
# }
# }
using Ruby on Rails 4, I have a UI where the user can select a video file from a directory path on a server. They then click a button that runs media info on the file and displays the xml for the video along with parsing certain data values from the xml and assigning the value to #variables and displaying it back in the UI html page. This is all done in the action/method 'evaluate media'. When the page loads back it determines if this file has been saved or not and allows the user to save the filename, path, and media info attributes to a table in mysql. When you click the save button it calls the acton/method 'save_file'. When I try to assign these variable values to the model class fields to insert into the table (within the controller). The values are not read. It only inserts nulls. How
can I have these variable values assigned in the 'evaluate_media' action also be available for the 'save_file' action or any other action within the same controller? Based on how they were setup and defined, I thought they were availble within the scope of the model/controller object 'file_alias_tfile'.
In the 'save_file' action here are the 3 different ways I tried to assign the value:
full_path = params[:filepath2] <--This one puts a NULL into the table
src_location = #radio_button_value <--This one puts a NULL into the table
directory = "#{#dir_path_choice}" <--This one doesn't even get called into the insert script and nothing is inthe column on insert. (I don't get errors and a record does geet inserted with the other good values.)into the table
Here is my save_file action/method code where I am trying to assign my variable values to the model fields:
def save_file
src_location = #radio_button_value
directory = "#{#dir_path_choice}"
full_path = params[:filepath2]
# "#{#filepathname}"
full_filename = "#{#filepath}"
alias_code = "#{#file_alias}"
validate_status = "#{#file_status}"
error_msg = "#{#file_msg}"
video_alias_match = "#{#msg_dtl1}"
audio_alias_match = "#{#msg_dtl2}"
video_format = "#{#video_format}"
video_bitrate = "#{#video_bitrate}"
video_width = "#{#video_width}"
video_height = "#{#video_height}"
video_framerate = "#{#video_framerate}"
video_aspect_ratio = "#{#video_aspectratio}"
video_scan_type = "#{#video_scantype}"
video_scan_order = "#{#video_scanorder}"
#file_alias_tfile = FileAliasTfile.new( :src_location => src_location, :directory => directory, :full_path => full_path, :full_filename => full_filename, :file_ext => '',
:assigned_status => 'Unassigned', :file_status => 'Saved', :alias_code => alias_code, :validate_status => validate_status, :error_msg => error_msg,
:video_alias_match => video_alias_match, :audio_alias_match => audio_alias_match, :video_format => video_format, :video_bitrate => video_bitrate,
:video_width => video_width, :video_height => video_height, :video_framerate => video_framerate, :video_aspect_ratio => video_aspect_ratio,
:video_scan_type => video_scan_type, :video_scan_order => video_scan_order, :video_alias_code => '', :audio_alias_code => '',
:bus_prod_initiative_id => 0, :status => 'Active', :start_date => DateTime.now.to_date, :end_date => '', :deleted_b => 0,
:created_by => 'admin', :updated_by => 'admin')
#file_alias_tfile = FileAliasTfile.create(file_alias_tfile_params)
if #file_alias_tfile.save
redirect_to mainpages_home_path, :notice => "The file alias validation has been saved."
else
redirect_to alias_mainpages_home_path, :notice => "The file alias validation has been saved."
# render = "index"
end
end
Here is the 'evaluate_media' method where the values called above in the save_file are defined:
def evaluate_media
#state = 'post'
#radio_button_value = params[:location]
#Determine if file chosen has been saved to database yet.
#stored_file = FileAliasTfile.where(:full_path => params[:filepath2], :deleted_b => 0).first
if #stored_file.present?
#file_exists_flag = 'Y'
#file_exists_msg = 'This File and Alias has been saved in application.'
else
#file_exists_flag = 'N'
#file_exists_msg = 'This File and Alias has NOT been saved in application yet.'
end
root_dir = '/watchfolder/miniprod/hot/'
provider_dir = ""
#Store selected value for re-display on post.
#selected_filepath = params[:filepath2]
filepath = File.join(root_dir, provider_dir, params[:filepath])
#filepath = File.join(params[:filepath2])
#media_xml = ::MediaInfo.call(#filepath) #Filepath is sent in from the index html
#alias_xml = ::AliasGenerator.call(#media_xml)
#media_xml_for = ""
#alias_xml_for = ""
REXML::Document.new(#media_xml).write(#media_xml_for, 1)
REXML::Document.new(#alias_xml).write(#alias_xml_for, 1)
alias_parse_doc = ""
media_parse_doc = ""
alias_parse_doc = REXML::Document.new(#alias_xml)
media_parse_doc = REXML::Document.new(#media_xml)
#parse Alias XML Doc
# #aliasgen_ver = alias_parse_doc.elements.each("/aliasGenerator vr=/text()") { |e| e }
#aliasgen_ver = REXML::XPath.each(alias_parse_doc, "/aliasGenerator vr=/text()") { |element| element }
#file_alias = REXML::XPath.each(alias_parse_doc, "*//alias/text()") { |element| element }
#file_status = REXML::XPath.each(alias_parse_doc, "*//error/text()") { |element| element }
#file_msg = REXML::XPath.each(alias_parse_doc, "*//error_m/text()") { |element| element }
#msg_dtl1 = REXML::XPath.each(alias_parse_doc, "*//closestvideoalias/text()") { |element| element }
#msg_dtl2 = REXML::XPath.each(alias_parse_doc, "*//closestaudioalias/text()") { |element| element }
#parse Video Media Info XML Doc
#filepathname = REXML::XPath.each(media_parse_doc, "*//Complete_name/text()") { |element| element }
#video_format = REXML::XPath.each(media_parse_doc, "//track[#type='Video']/Format/text()") { |element| element }
#video_bitrate = REXML::XPath.each(media_parse_doc, "//track[#type='Video']/Bit_rate/text()") { |element| element }
#video_width = REXML::XPath.each(media_parse_doc, "//track[#type='Video']/Width/text()") { |element| element }
#video_height = REXML::XPath.each(media_parse_doc, "//track[#type='Video']/Height/text()") { |element| element }
#video_aspectratio = REXML::XPath.each(media_parse_doc, "//track[#type='Video']/Display_aspect_ratio/text()") { |element| element }
#video_framerate = REXML::XPath.each(media_parse_doc, "//track[#type='Video']/Frame_rate/text()") { |element| element }
#video_scantype = REXML::XPath.each(media_parse_doc, "//track[#type='Video']/Scan_type/text()") { |element| element }
#video_scanorder = REXML::XPath.each(media_parse_doc, "//track[#type='Video']/Scan_order/text()") { |element| element }
#parse Audio Media Info XML Doc
# #audio_track = REXML::XPath.each(media_parse_doc, "//track[#type= 'Audio']/track/text()") { |element| element }
# #track_array = REXML::XPath.each(media_parse_doc,(#audio_track)) do {|track| track.elements["Bit_rate"].text }
# #bitrate = track.elements["Bit_rate"].text
# end
##audio_tracknum = REXML::XPath.each(media_parse_doc, "//track[#type='Audio']/track streamid=/text()") { |element| element }
# #audio_format = REXML::XPath.each(media_parse_doc, "//track[#type='Audio']/Format/text()") { |element| element }
# #audio_bitrate = REXML::XPath.each(media_parse_doc, "//track[#type='Audio']/Bit_rate/text()") { |element| element }
# #audio_numchan = REXML::XPath.each(media_parse_doc, "//track[#type='Audio']/Width/text()") { |element| element }
# #audio_language = REXML::XPath.each(media_parse_doc, "//track[#type='Audio']/Display_aspect_ratio/text()") { |element| element }
render :action => :index
end
Can you please provide me an example of how I can either setup my variables correctly to pass across actions and/or how to properly assign them in the insert to the database?
Your help is appreciated!
I found the answer in another question for my search but it still leaves an open question.
Here is the link for the other question and answer for more details:
Same instance variable for all actions of a controller
Basically it gave me 2 approaches. If my one action is not rendering from the other, and both methods need to access the values, then I will need to define another method where I assign the variables and then have both save_file and evaluate_media methods call this newly define method so they too can access the variables. Here is the example where the question addressed the index and show methods sharing the same variable.
def index
set_up_instance_variable
end
def show
set_up_instance_variable
end
private
def set_up_instance_variable
#some_instance_variable = foo
end
The other solution is using the before_filter:
You can define instance variables for multiple actions by using a before filter, e.g.:
class FooController < ApplicationController
before_filter :common_content, :only => [:index, :show]
def common_content
#some_instance_variable = :foo
end
end
Now #some_instance_variable will be accessible from all templates (including partials) rendered from the index or show actions.
Looking for a way to mock spring security in some unit/integration tests.
Grails: V2.1.0
Spring Security Core: V1.2.7.3
Controller has the following:
// some action
def index(){
def user = getLoggedInUser()
render ....
}
...
private getLoggedInUser(){
return User.get(springSecurityService.principal.id)
}
I tried the following and various other ways but can't see to get it to work:
void testSomething(){
def dc = new SomeController()
dc.springSecurityService = [
encodePassword: 'password',
reauthenticate: { String u -> true},
loggedIn: true,
principal: [username:"Bob"]]
dc.index()
... assertion....
It seems that the user is not getting created and can't get the principal.id. Any suggestions or better alternatives?
I think the user is just being created, but not saved, and that's why it doesn't have an ID.
The solution could be this:
void testSomething(){
def dc = new SomeController()
def loggedInUser = new User(username: "Bob").save() // This way the user will have an ID
dc.springSecurityService = [
encodePassword: 'password',
reauthenticate: { String u -> true},
loggedIn: true,
principal: loggedInUser]
dc.index() ... assertion....
There's an alternative:
void testSomething(){
def dc = new SomeController()
def loggedInUser = new User(...).save()
dc.metaClass.getLoggedInUser = { loggedInUser }
...
I would suggest a refactor to getLoggedInUser:
private getLoggedInUser(){
return springSecurityService.currentUser
}
With this change, you could write:
void testSomething(){
def dc = new SomeController()
def loggedInUser = new User(...).save()
dc.springSecurityService = [
encodePassword: 'password',
reauthenticate: { String u -> true},
loggedIn: true,
getCurrenUser: { loggedInUser }]
...
im using rails 3 app. and i cant save my datetime value from my datetime picker to my database in sql server 2005. i keep getting invalid date. any suggestions?
i have this in my model:
scope :available, lambda {
|checkin, checkout| {
:select => 'amenities.*',
:order => 'id',
:conditions => ["
amenities.id NOT IN
(
SELECT aa.id from amenities aa, amenity_list al WHERE
aa.id = al.amenities_id AND
(
(? BETWEEN al.checkin AND al.checkout) OR
(? BETWEEN al.checkin AND al.checkout)
)
)",
checkin, checkout
]
}
}
here's my controller:
def step2
#cart = current_cart
checkin = params[:checkin]
checkout = params[:checkout]
#amenities = Amenity.available(checkin, checkout)
session[:checkin] = checkin
session[:checkout] = checkout
end
application.js
$(function() {
var dates = $( "#checkin, #checkout" ).datetimepicker({
dateFormat: 'mm/dd/yyyy hh:MM:ss TT',
buttonImageOnly: true,
buttonImage: 'images/icons/cal.png',
showOn: 'button',
showAnim: 'blind',
defaultDate: "+1w",
changeMonth: false,
numberOfMonths: 2,
minDate: new Date(),
onSelect: function( selectedDate ) {
var option = this.id == "checkin" ? "minDate" : "maxDate",
instance = $( this ).data( "datetimepicker" ),
date = $.datetimepicker.parseDate(
instance.settings.dateFormat ||
$.datetimepicker._defaults.dateFormat,
selectedDate, instance.settings );
dates.not( this ).datetimepicker( "option", option, date );
}
});
});
Have you tried Date.parse(checkin) ?