I have a method in controller that calls another method created in a module like this example:
def example
#var1 = ModuleName::ClassName.get()
respond_to do |format|
format.json { render json: #var1}
end
end
The method get() goes to a website looking for information and returns an array.
Everything works perfectly, but I wonder if in the controller there is a way to set a timeout if the application takes a long time to run! Is it possible?
here is one way (a more general way) you could do that..
def example
Timeout::timeout(40) do # 40 sec, change it to anything you like
#var1 = ModuleName::ClassName.get()
rescue Timeout::error
# do something (maybe set #var1's value if it couldn't get desired array)
end
respond_to do |format|
format.json { render json: #var1}
end
end
If under ModuleName::ClassName.get() you imply some kind of third-party ruby http library, then it's likely that you should set some kind of timeout parameter (depends on library). You just pass a desired timeout in seconds (or whatever measurement you want).
Thus the pseudo-code might look like this:
ModuleName::ClassName.get(10)
For more detailed answer, can you please be more specific about how are you doing a call to external service?
Related
I have an application that renders a div that inside of it has links, that updates the look of this div using AJAX. The issue is Rails has to go and request the same data over and over when switching the view which seem inefficient.
After reading up on the subject of sharing variables between controller actions I understand that this is not possible due to the stateless nature. Have also read that session should not be used to store object, and these variables contain lots of data, mainly used to generate graphs. Another option I guess would be Caching which I'm not very familiar with. Or saving the variables in Javascript on the browser possibly.
Anyone had a similar problem that could provide some guiding?
class ArtistsController < ApplicationController
def index
if params[:term]
respond_to do |format|
format.html
format.js {render "show.js.haml"}
end
else
#artists= Artist.all
end
end
def show
#days=90
# DATABASE QUERIES
#artist= Artist.find(params[:id])
#reach_period= Reachupdate.period(#artist.id,#days)
#update_period=Update.period(#artist.id,#days)
#songs_load= Song.by_artist(#artist.id).joins(:playlists)
#song_period= #songs_load.period(#days)
# CHART
#updates= ChartTransformation::pop_chart(#update_period,#days)
#reach = ChartTransformation::reach_chart(#reach_period,#days)
#dates= ChartTransformation::dates(#days,3)
#reach_labels= ChartTransformation::reach_labels(#reach_period,2)
#songs= ChartTransformation::data_to_releases(#song_period, #days)
#reach_diff = Reachupdate.diff(#reach_period)
#pop_diff = Update.diff(#update_period)
#playlisting= ChartTransformation::playlisting(Playlist.by_artist(#artist.id),#days)
end
def overview
#days=90
# DATABASE QUERIES
#artist= Artist.find(params[:id])
#reach_period= Reachupdate.period(#artist.id,#days)
#update_period=Update.period(#artist.id,#days)
#song_period= Song.by_artist(#artist.id).period(#days)
# CHART
#updates= ChartTransformation::pop_chart(#update_period,#days)
#reach = ChartTransformation::reach_chart(#reach_period,#days)
#dates= ChartTransformation::dates(#days,3)
#reach_labels= ChartTransformation::reach_labels(#reach_period,2)
#songs= ChartTransformation::data_to_releases(#song_period, #days)
#reach_diff = Reachupdate.diff(#reach_period)
#pop_diff = Update.diff(#update_period)
#playlisting= ChartTransformation::playlisting(Playlist.by_artist(#artist.id),#days)
respond_to do |format|
format.js {render "timeline_content.js.haml"}
end
end
end
Another option I guess would be Caching which I'm not very familiar with
you will have to make yourself familiar with caching. it's the answer to your question.
in your case, it would do a fragment-caching in the view, read the guides https://guides.rubyonrails.org/caching_with_rails.html#fragment-caching
I wonder if there is any explanation of the usage below under http://api.rubyonrails.org/ instead of http://guides.rubyonrails.org.
render json: #user
Although there is a page in Rails Guide mentioning this, it does not cover other available options like :include, for example:
render json: #user, include: { blog: { only: [:name, :permalink]} }
I can't believe such common API is hard to find in its official API document.
That's probably because it's using as_json method. Refer to:
https://apidock.com/rails/ActiveModel/Serializers/JSON/as_json
So, the render method isn't strictly related to as_json options. You should head to the link above.
Dug around a little and found the ActionController::Renderers documentation which, to add a new one states:
To create a renderer pass it a name and a block. The block takes two arguments, the first is the value paired with its key and the second is the remaining hash of options passed to render.
and then if you view it's source on GitHub you can see when they create the :json renderer, they do:
add :json do |json, options|
json = json.to_json(options) unless json.kind_of?(String)
...
end
So, Rails, is just calling to_json on "the value paired with it's key" (which is #user in render json: #user) passing in all the extras you passed to the render call, in this case the include.
So if you want to know what the include option is doing, you would need to check the #user.to_json method, which then calls ActiveSupport::JSON.encode which just kind of delegates to ActiveSupport::JSON::Encoding::JSONGemEncoder#encode which then just calls as_json on the object and turns it into a string.
Reviewing a coworker's PR I came across a pattern I have not seen before, where a private method was called and or return appended to the end if that method failed. I found a blog post mentioning this (number 2) but it feels strange to me.
The code sort of looks like this:
class OurController < ApplicationController
def index
amount = BigDecimal.new(params[:amount]).to_i
if amount < 0
cancel_processing(amount) or return
else
process(amount)
end
render json: {success: true}
end
private
def cancel_processing(amount)
response = CancelProcessingService.call(amount)
if response
log_stuff
else
render json: {error: true} and return
end
end
end
Since the render error is being called from within the method, it's not ending, and it's therefore going to the end of the index action and double rendering (without the or render after cancel_processing).
This feels like a smell to me. renders and returns are respected within before_filters, so them not being respected in methods feels inconsistent. Maybe it just feels wrong because I haven't encountered this or return pattern before, but I ask: is there a way to get Rails to respect render... and returns from within methods (which are not before_filters or actions)?
I feel like advocating for rewriting these methods to simply return JSON, and pass the response to render later on in the method -- but if this is a normal pattern then I have no ground to suggest that.
What are your thoughts?
render ... and/or return is a bogus pattern. Rails documentation uses it in a couple of places but I believe it should not. It's bogus because although render returns a truthy value (the rendered response body) when it succeeds, when it fails it does not return a falsy value but raises an error. So there is no point in handling the nonexistent case when it returns a falsy value. (The same applies to redirect_to.)
In an action, to avoid misleading anyone about how render works, just do
render # options
return
to render and then exit.
In a private method called by an action, you can't say return and exit from the calling action, because Ruby methods don't work that way. Instead, make the method return a value that the action can interpret and return early if appropriate. Something like this:
def index
amount = BigDecimal.new(params[:amount]).to_i
if amount < 0
if !cancel_processing(amount)
return
end
else
process(amount)
end
render json: {success: true}
end
def cancel_processing(amount)
response = CancelProcessingService.call(amount)
if response
log_stuff
else
render json: {error: true}
end
response
end
In a controller you can call performed? to find out if a render/redirect has already been called. For example:
performed? # => false
render json: {error: true}
performed? # => true
My rails app produces XML when I load /reports/generate_report.
On a separate page, I want to read this XML into a variable and save it to the database.
How can I do this? Can I somehow stream the response from the /reports/generate_report.xml URI into a variable? Or is there a better way to do it since the XML is produced by the same web app?
Here is my generate_report action:
class ReportsController < ApplicationController
def generate_report
respond_to do |format|
#products = Product.all
format.xml { render :layout => false }
end
end
end
Here is the action I am trying to write:
class AnotherController < ApplicationController
def archive_current
#output = # get XML output produced by /reports/generate_report
# save #output to the database
respond_to do |format|
format.html # inform the user of success or failure
end
end
end
Solved: My solution (thanks to Mladen Jablanović):
#output = render_to_string(:file => 'reports/generate_report.xml.builder')
I used the following code in a model class to accomplish the same task since render_to_string is (idiotically) a protected method of ActionController::Base:
av = ActionView::Base.new(Rails::Configuration.new.view_path)
#output = av.render(:file => "reports/generate_report.xml.builder")
Perhaps you could extract your XML rendering logic to a separate method within the same controller (probably a private one), which would render the XML to a string using render_to_string, and call it both from generate_report and archive_current actions.
What I typically do in this type of situation is to create a separate module/class/model to generate the report (it could even potentially be right in the Product model). This separate component could be in app/models or it could be in lib. In any case, once you have it extracted you can use it anywhere you need it. The controller can call it directly. You can generate it from the console. You can have a cron job generate it. This is not only more flexible, but it also can help smooth out your request response times if the report becomes slow to generate.
Since you are using a template it's understandable that the controller route is convenient, but even if you have to include some kind of ruby templating system in your auxiliary lib, it's still probably going to be less hassle and more flexible then trying to go through the controller.
#output = Product.all.to_xml
I'm sorry, is you question about Xml or about sessions? I mean is the fact that your action generates Xml material to the question? Or do you just want to save the output of the action for latter use?
You said on a "separate" page - you mean on another request? (like after user approved it?)
Why do you want to save the output? Because it should be saved exactly as rendered? (for example user can get frustrated if he clicked to save one report and you saved another)
Or is this thing expensive to generate?
Or may be, I got it wrong and it's about refactoring?
Would someone be able to break down the Ruby specifics of what each of these statements consist of in as far as methods, parameters, block interpretations etc. This is very common to see in Rails code and I'm trying to understand how the Ruby interpreter reads this code:
respond_to do |format|
format.xml { render :layout => false }
end
In as far as I understand, respond_to is a method that's taking one parameter to it, a block. So I'm guessing it's written something like:
def respond_to(&block)
block.call
end
.. or something similar?
in the block itself, format is the object respond_to passes into the block and xml is what the request is set to, at which point it calls a block in itself if the request is asking for XML type data and goes ahead and invokes a render method, passing it a keyword based argument, :layout => false?
Would someone clean up my understanding of how they above works. This type of code is all over Rails and I'd like to understand it before using it more.
This is a typical Implementation Pattern for Internal DSLs in Ruby: you yield an object to the block which then itself accepts new method calls and blocks and thus guides the interface. (Actually, it's pretty common in Java, too, where it is used to get meaningful code completion for Internal DSLs.)
Here's an example:
def respond_to
yield FormatProxy.new(#responders ||= {})
end
class FormatProxy
def initialize(responders)
#responders = responders
end
def method_missing(msg, *args, &block)
#responders[msg] = [args, block]
end
end
Now you have a mapping of formats to executable pieces of code stored in #responders and you can call it later and in a different place, whenever, whereever and however often you want:
respond_to do |f|
f.myformat { puts 'My cool format' }
f.myotherformat { puts 'The other' }
end
#responders[:myformat].last.call # => My cool format
#responders[:myotherformat].last.call # => The other
As I hinted at above, if instead of a dumb proxy object that simply uses method_missing, you were to use one which had the most important methods (xml, html, json, rss, atom and so on) predefined, a sufficiently intelligent IDE could even give you meaningful code completion.
Note: I have absolutely no idea whether this is how it is implemented in Rails, but however it is implemented, it is probably some variation of this.
You've basically got it, and the source code is readable enough to figure out what's going on. When you want to source dive something like this, there are only a few steps needed.
1. Figure out where Rails is.
$ gem environment
RubyGems Environment:
- RUBYGEMS VERSION: 1.3.5
- RUBY VERSION: 1.8.7 (2009-06-12 patchlevel 174) [i686-darwin9.8.0]
- INSTALLATION DIRECTORY: /opt/ruby-enterprise-1.8.7-2009.10/lib/ruby/gems/1.8
...
2. Figure out where in Rails the code is.
$ cd /opt/ruby-enterprise-1.8.7-2009.10/lib/ruby/gems/1.8/gems # installation directory from above + "/gems"
$ ack "def respond_to"
...
actionpack-2.3.5/lib/action_controller/mime_responds.rb
102: def respond_to(*types, &block)
...
3. Dive in.
$ vim actionpack-2.3.5/lib/action_controller/mime_responds.rb
If you have such kind of questions or not sure how things work, the best way to find it out is to go to the source (which in Ruby is very readable).
For this particular question, you can go to mime_respond.rb. Line 187 ATM.
The comment explains:
# Here's the same action, with web-service support baked in:
#
# def index
# #people = Person.find(:all)
#
# respond_to do |format|
# format.html
# format.xml { render :xml => #people.to_xml }
# end
# end
#
# What that says is, "if the client wants HTML in response to this action, just respond as we
# would have before, but if the client wants XML, return them the list of people in XML format."
# (Rails determines the desired response format from the HTTP Accept header submitted by the client.)
Additionally respond_to takes a block OR mime types to respond with.
I would really recommend to have a look at the code there.
The comments are very comprehensive.
def respond_to(&block)
block.call
end
This is the definition of a method with one parameter. The & tells the interpreter that the parameter may also be given, when we're gonna' call the method, in the block do ... end form: respond_to do puts 1 end. This parameter can also be any object that responds to a call metod (like a Proc or a lambda):
a = lambda{ puts 1 }; respond_to(a)
respond_to do |format|
format.xml { render :layout => false }
end
This calls the respond_to method with one parameter, the do ... end block. In the implementation of this second respond_to method this block is called similar to the following:
def respond_to(&block)
block.call(#format) # or yield #format
end
so in order to conform to the 1 parameter call, our block of code must also accept 1 parameter, which in the do ... end' syntax is given between the bars|format|`