I have the following code in my model:
def getFormattedAverages
averages = Array.new();
self.items.each do |i|
x = self.responses.average(:x,:conditions=>['item_id = ?',i.id])
if x.nil?
x = 2000
else
x = x.to_i
end
y = self.responses.average(:y,:conditions=>['item_id = ?',i.id]).to_i
if y.nil?
y = "*"
end
averages.push([[x,y]])
end
return averages
end
In the view I have:
var dataseries = <%=#question.getFormattedAverages%>;
On my development machine, I get the data in exactly the form I need to pass into my graphing function. It looks like this when I "view source" on the rendered page:
var dataseries = [[[31, 34]], [[45, 33]], [[34, 23]], [[10, 27]], [[21, 37]]];
But when I run it on my production server, it looks like this-
var dataseries = -6745-798571322000010791-2270-18;
Note that the x and y data on my development and production servers is different. The point is that all of the brackets and commas are being stripped out. Any help you can provide would be much appreciated - this one really has me stumped!
I found this answer.
Changing the code in my view to read
var dataseries = <%=raw #question.getFormattedAverages.to_json%>;
seems to work!
Related
I want to make an array of hashes. But the problem is after first iteration when code goes to next line then it directly replaces the content of array.
#item_name =[]
item = {}
#invoiceinfo.each do |invoice|
item[:name] = Invoiceinfo.find(#invoiceinfo.id).item.name
item[:desc] = Invoiceinfo.find(#invoiceinfo.id).desc
item[:unit_price] = Invoiceinfo.find(#invoiceinfo.id).unit_price
byebug
#item_name.push (item)
end
This is what i am getting
after first iteration suppose i have this data
#item_name = [{:name=>"usman", :desc=>"sample ", :unit_price=>100}]
As soon as next line is executed it directly changes #item_name(name variable)
After executing item[:name] = Invoiceinfo.find(#invoiceinfo.id).item.name
the content of the #item_name is changed
#item_name = [{:name=>"next_name", :desc=>"sample ", :unit_price=>100}]
Any help would be appreciated.
Thannks
Try something like this
#item_name = []
#invoiceinfo.each do |invoice|
invoice_info = Invoiceinfo.find(#invoiceinfo.id)
item = {}
item[:name] = invoice_info.item.name
item[:desc] = invoice_info.desc
item[:unit_price] = invoice_info.unit_price
#item_name.push(item)
end
If you consider using ruby paradigms and best practices in ruby code, this mistake won’t happen in the future.
#item_name = #invoiceinfo.each_with_object([]) do |invoice, acc|
invoice_info = Invoiceinfo.find(#invoiceinfo.id)
acc.push(
name: invoice_info.item.name,
desc: invoice_info.desc
unit_price: invoice_info.unit_price
)
end
I'm writing a forum application in Rails and I'm stuck on limiting nested quotes.
I'm try to use regex and recursion, going down to each matching tag, counting the levels and if the current level is > max, deleting everything inside of it. Problem is that my regex is only matching the first [ quote ] with the first seen [ /quote ], and not the last as intended.
The regex is just a slight tweak of what was given in the docs of the custom bbcode library I'm using (I know very little about regex, I've tried to learn as much as I can in the past couple days but I'm still stuck). I changed it so it'd include [quote], [quote=name] and [quote=name;222] . Could someone examine my code and let me know what the problem could be? I'd appreciate it lots.
def remove_nested_quotes(post_string, max_quotes, count)
result = post_string.match(/\[quote(:.*)?(?:)?(.*?)(?:)?\](.*?)\[\/quote\1?\]/mi)
if result.nil?
return false
elsif (count = count+1) > max_quotes
full_str = result[0]
offset_beg = result.begin(3)
offset_end = result.end(3)
excess_quotes = full_str[offset_beg ..offset_end ]
new_string = full_str.slice(excess_quotes )
return new_string
else
offset_beg = result.begin(3)
offset_end = result.end(3)
full_str = result[0]
inner_string = full_str[offset_beg..offset_end]
return remove_nested_quotes(inner_string , max, count)
end
end
I mean something like
counter = 0
max = 5
loop do
matched = false
string.match /endquote|quote/ do |match|
matched = true
if endquote matched
counter -= 1
else # quote matched
counter += 1
end
if counter > max
# Do something, break or return
else
string = match.post_match
end
end
break unless matched
end
Im learning Redis and trying it to run with rails and backbone. I need to GET/SET 50 values every 66ms on my front-end. I need to have objects (#monsters) with redis and i did them this way. I dont really know or its becouse my computer slow or code weak, or backbone's beginners code is slowing my calculations, but after 3 seconds all PUT/GET to database pending and everything working slower and slower. I'm debugging with localhost, maybe when i push to heroku it is fast enough to update all data becouse of heroku servers? or not? How could i improve the dataSET/dataGET?
My random Redis key and value in console looks like:
2.1.2 :002 > $redis.get('1001')
=> "[452,305,452,316,3]"
# (X position, Y position, Targets X position, Targets Y position, Level)
i have 50 keys named from '1001' to 1050' with values of each monster Xpos, Ypos, XposDest, YposDest positions which gonna be on canvas map. These are parsed to objects with Rails and fetched to backbone.
# Getting all values from Redis database and sending to backbone.
class MainController < ApplicationController
def index
m = []
for key in $redis.keys do
value = JSON.parse($redis.get(key))
m.push id: key.to_i,
Xpos: value[0],
Ypos: value[1],
XposDest: value[2],
YposDest: value[3],
level: value[4]
end
#monsters = m
end
# Getting all values from Backbone and updating Redis database.
class MonstersController < ApplicationController
def update
id = monster_params[:id]
xpos = monster_params[:Xpos]
ypos = monster_params[:Ypos]
xposDest = monster_params[:XposDest]
yposDest = monster_params[:YposDest]
level = monster_params[:level]
$redis.set id, [xpos,ypos,xposDest,yposDest,level].to_json
respond_to do |format|
format.html do
render nothing: true
end
end
end
private
def monster_params
params.require(:monster)
end
end
here goes my backbone important part
Sprint.Views.Maps ||= {}
class Sprint.Views.Maps.IndexView extends Backbone.View
initialize: ->
if move_on_count is 0
#addAll()
#game_init_function()
mob_x_post = []
mob_y_post = []
mob_x_posdest = []
mob_y_posdest = []
move_on_count = 0
game_init_function: ->
#receiving_attributes_from_database()
#move_on()
move_on: ->
move_on_count++
self = this
timer 66, ()-> self.fetch_mobs_from_redis_db()
fetch_mobs_from_redis_db: ->
self = this
#addAll
#save_mobs_position()
#receiving_attributes_from_database()
addAll: () =>
#options.monsters.each(#addOne)
addOne: (monster) =>
monstersas.push monster
mobbys.push monster.attributes.level
save_mobs_position: ->
for alfa in [0..(monstersas.length-1)]
#options.monsters.models[alfa].save((level: alfa+1, YposDest: parseInt(mob_y_posdest[alfa]), XposDest: parseInt(mob_x_posdest[alfa]), Ypos: parseInt(mob_y_post[alfa]), Xpos: parseInt(mob_x_post[alfa])))
receiving_attributes_from_database: ->
for cnt in [0..(monstersas.length-1)]
mob_y_post[cnt] = monstersas[cnt].attributes.Ypos
mob_x_post[cnt] = monstersas[cnt].attributes.Xpos
mob_y_posdest[cnt] = monstersas[cnt].attributes.YposDest
mob_x_posdest[cnt] = monstersas[cnt].attributes.XposDest
# here goes big canvas code..
Im still learning rails, backbone, coffeescript, redis.. Here i believe are so many things that could make my game running slow..
In Rails with HAML, I want to create a simple line of spaces: ====== on the page, with variable length. However, the following code:
- 10.times do
\=
renders the following:
= = = = = = = = = =
I want to get rid of the spaces in the middle of these equals signs, but I don't really have any idea how. I know with ERB you can use
<%= 10.times do -%>=<% end %>
but I'm having trouble figuring out how to do it here.
Another approach, tested, should work:
= "=" * 10
This should work
- 10.times do
&= "="
I am working on a script that is supposed to be writing a list of items to a hash, but for some reason its only placing the last item in the loop in the hash... I have been working on this script all day, so I am pretty sure its something I am just missing.
Here is the script
#mr = MediaRating.where("user_id = ?", session['user_credentials_id'])
#mr.each do |rating|
#m = Media.where("id = ?", rating.media_id)
#m.each do |m|
s = Profile.find_by_subscriber_id(m.subscriber_id)
#h_lang = Language.find_by_code(s.language)
#history = {m.title => #h_lang.english}
end
end
There are multiple records in the MediaRating table so I know it has to do something with how my loop is. Thanks in advance for the help!
Working code:
#mr = MediaRating.where("user_id = ?", session['user_credentials_id'])
#mr.each do |rating|
#m = Media.find(rating.media_id)
s = Profile.find_by_subscriber_id(#m.subscriber_id)
#h_lang = Language.find_by_code(s.language)
#history[#m.title] = #h_lang.english
end
In the last line, you are over-writing the entire #history hash instead of adding a new key/value pair to it. I'm guessing that isn't what you intended. Change this line:
#history = {m.title => #h_lang.english}
to this:
#history[m.title] = #h_lang.english