I want to use 'tinymce_spellcheck' to use the spellcheck button in my tinymce editor.
I wrote in my controller:
def spellcheck
data = ActiveSupport::JSON.decode(request.raw_post)
args = data['params'].to_a.first
spellcheck = TinymceSpellcheck.new({}, :raspell)
result = spellcheck.send(data['method'].underscore,*args) #****---- THIS LINE****
render :json => { :id => data['id'], :result => result, :error => nil }.to_json
end
I get the following error message:
ArgumentError (wrong number of arguments (1 for 2)):
app/controllers/members_controller.rb:127:in `spellcheck'
Would you be so kind to tell me how to solve this problem? I am providing two arguments and, yet, I get the same error message again and again.
Well, the problem is probably that args is empty or nil, so when you call the splat on it, it turns into zero arguments. Thus, your only argument is the 'method', and you get an ArgumentError.
def spellcheck
`data = ActiveSupport::JSON.decode(request.raw_post)
args = data['params'].to_a.first
spellcheck = TinymceSpellcheck.new({}, :raspell)
result = spellcheck.send(data['method'].underscore,*args)
render :json => { :id => data['id'], :result => result, :error => nil }.to_json
end`
The line `args = data['params'].to_a.first` was changed to`args = data['params'].to_a`
Related
This seems like a duplicate question but the answers on the others posts don't seem to work for my issue here.
I'm needing to render two JSON items here within my index method in my controller:
def index
#user = User.all
#libraries = Library.all.order(:created_at)
user_cards = current_user.libraries
render :json => #libraries, :include => :user
render :json => user_cards
end
I attempted to do it this way (failed with a 500 error):
render :json => #libraries, user_cards, :include => :user
And I also attempted to do it this way (also failed with a 500 error): render :json => #libraries :include => [:user, :user_cards]
UPDATE
This is the most recent attempt as rendering the json properly:
def index
#user = User.all
#libraries = Library.all.order(:created_at)
user_cards = current_user.libraries
render json: {
user_cards: user_cards,
libraries: #libraries.as_json(include: [:user])
}
end
The issue with this is that I am now getting an error on libraries throughout my application as it stands. If I simply just render json like I originally had it (render :json => #libraries, :include => :user), I do not get this error. So, I'm assuming the way I have it is still not correct. The exact error on libraries is being called within one of my React components where I use filter:
Error: Uncaught TypeError: this.props.librarys.filter is not a function
Error Location:
let filteredCards = this.props.librarys.filter(
(library) => {
return library.title.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1 || library.desc.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1
}
)
Controller can only return one response, you can achieve this with combining this two returns into one:
respond_to do |format|
format.json { render json: { user_cards: user_cards,
libraries: #libraries } }
end
While I'm parsing alliance feed in a Sinatra/Ruby app I get the error:
/opt/rh/ruby200/root/usr/share/ruby/net/http/response.rb:368: [BUG]
Segmentation fault ruby 2.0.0p645 (2015-04-13) [x86_64-linux]
I'm wondering if this is a bug with Ruby or something wrong with the code, and if so, what could I do to fix it?
Link to the error
This is the code for the parsing alliance feed:
feeds.each { |name, hash|
puts "=== PARSING #{name.upcase} FEED ==="
start = Time.now
open(hash[:url]) { |feed|
send(hash[:action], feed)
}
duration = Time.now - start
puts "Feed syndication completed in #{duration.to_s} seconds."
puts
}
# Close DB connection
puts "Disconnecting"
#db.disconnect
end
def parseAllianceData(xml)
start = Time.now
allianceData = XMLObject.new xml
duration = Time.now - start
puts "XML parsed in #{duration.to_s} seconds."
puts "Alliances found: #{allianceData.alliances.count}"
#db[:feeds].insert(
:generated_at => allianceData.server.datagenerationdatetime,
:type => "Alliance",
:is_current => true)
start = Time.now
allianceData.alliances.each { |alliance|
capital_last_moved_at = (alliance.alliancecapitallastmoved rescue nil)
taxrate_last_changed_at = (alliance.alliancetaxratelastchanged rescue nil)
#db[:alliance].insert(
:id => alliance.alliance[:id],
:ticker => alliance.allianceticker,
:name => alliance.alliance,
:founded_at => alliance.foundeddatetime,
:founded_by_player_id => alliance.foundedbyplayerid[:id],
:capital_town_id => alliance.alliancecapitaltownid[:id],
:member_count => alliance.membercount,
:total_population => (alliance.totalpopulation rescue 0),
:tax_rate => (alliance.alliancetaxrate.to_i) / 100.0,
:tax_rate_last_changed_at => taxrate_last_changed_at,
:capital_town_last_moved_at => capital_last_moved_at)
alliance.roles.each { |role|
#db[:alliance_roles].insert(
:id => role.role[:id],
:name => role.role,
:alliance_id => alliance.alliance[:id],
:hierarchy_id => role.heirarchy[:id])
}
}
duration = Time.now - start
puts "Database populated in #{duration.to_s} seconds."
I spot one dangerous line of code in your sample:
send(hash[:action], feed)
It takes some string from external source (hash[:action]) and turns it into a method call. It is very dangerous, because you never know what string you will get. There could be a string there that cannot be made into a method call so Ruby crashes.
I would suggest checking for all supported actions and calling methods explicitly. You can do it with a case statement, for example.
action = hash[:action]
case action
when 'action1'
call_method1
when 'action2'
call_method2
else
puts "unsupported action: #{action}"
end
I'm having a hard time getting something which should be incredibly simple to work.
I've got an online quiz with multiple choice questions and a pass/fail mark. I've got everything working correctly bar the damned emailer function at the end. No matter whether passed is set to true or false it's always sending out the passed email. Have I done something a bit daft in this code which I just can't see or am I going to have to go back through everything with a fine-tooth comb?
def finalize
quiztype = params[:quiztype]
slug = params[:slug]
#qd = Quizdata.where(quiztype: quiztype, usertoken: slug).take
if #qd
#qd.completed = true
quizdata = JSON.parse(#qd.quizdata)
quizdata["completed"] = true
#qd.quizdata = quizdata.to_json
#qd.passed = params[:passed]
if #qd.save
if params[:passed]
QuizMailer.results_email_user(quizdata, #qd).deliver
else
QuizMailer.results_email_user_failed(quizdata, #qd).deliver
end
QuizMailer.results_email_client(quizdata, #qd).deliver
render json: { errors: [] }
else
render :json => { :errors => #qd.errors.full_messages }, :status => 422 #Unprocessable entity
end
else
render :json => { :errors => [ "Record not found" ] }, :status => 404
end
end
Here you go:
Replace
if params[:passed]
with
if ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES.include?(params[:passed])
It was failing because, you are getting result in String format (not nil, which makes it return true always), instead of Boolean.
Hope it helps!
Parameters are passed as strings.
Should have been:
if params[:passed] == "true"
QuizMailer.results_email_user(quizdata, #qd).deliver
else
QuizMailer.results_email_user_failed(quizdata, #qd).deliver
end
I am new to WSDL.
Code (I have added in the view directly - for test): (Page: http://localhost:3000/ccapis )
require 'savon'
client = Savon::Client.new(wsdl: "http://localhost:3000/ccapis/wsdl")
result = client.call(:fetch_prizes, message: { :gl_id => "123456789" })
result.to_hash
And in the controller:
soap_action "fetch_prizes",
:args => { :gl_id => :string },
:return => [:array]
def fetch_prizes
glnumber = params[:gl_id ]
prize = Prize.where(:gl_id => glnumber)
prize_to_show = []
a_hash = {}
prize.each do |p|
a_hash = { :prize => p.prize.to_s, :score => p.score.to_s, :date => p.round_date.to_s }
prize_to_show.push a_hash
a_hash = nil
end
render :soap => prize_to_show
end
When I try and run this in the Console all are good and I can see the result.to_hash but when I go to http://0.0.0.0:3000/ccapis I get the error that I mentioned above.
Explanation of what I am trying to achieve:
I need to supply a WSDL for a client which fetches all the prizes based on a score.
If My approach is wrong please direct me to a document so I can have a read and get a better understanding. Thanks again.
controller code:
def create
if current_user.id != params[:friend_id]
#return = { :curr_user_id => current_user.id, :params_id => params[:friend_id], :debug => 1 }
else
#return = { :curr_user_id => current_user.id, :params_id => params[:friend_id], :debug => 2 }
end
render :json => ActiveSupport::JSON.encode( #return )
end
so current_user.id is 1 and params[:friend_id] is being passed via an ajax call and its value is also 1
the problem is that it always returns true when it should return false in this case... is there anything that has to do with the number 1 being parsed as string instead of integer?
params are always strings, use:
if current_user.id != Integer(params[:friend_id])
I don't recommend to_i, look why:
"abc".to_i # => 0 which is unexpected
Integer("abc") # => raises error, which is fine