how to manage lifetime of variable for multiple request - ruby-on-rails

I have a variable in create method in controller ,is there any way to reuse that variable with the same value in update method. How can i pass this, or how can i maintain the lifetime for the multiple requests?
Example variable:
#m = Issue.where( :project_id => #project.id ).where( :issue => "xyz" )

As I understand it, your requirement is to re-use data that was accessed during one call to your API (for creation of an API entity), during a separate call (an update). The data is fetched from the database in the first case.
Just fetch the data again, using the same query.
The database is the only data source easily accessible in both events, that will reliably hold an up-to-date value.
As this is for a RESTful API, there should be no other state information - everything should be in either the current request or the database.
If you want, you can cache data for performance, but Ruby variables are not a reliable or efficient way to do that (because there will be several Ruby processes running independently on the web server, and you don't get to manage them from the controller code) - instead you might want to consider something like memcached if the query is slow and its results are needed in many API events. However, you should normally avoid caching data except where you have a real performance issue - because you will probably need to handle cache invalidation, too.

Related

Pagination with Alamofire and realm.io

I have an api which could look like http://URL/news/:lastloaded/:size where lastloadedand size is the range of objects the api should return. This api returns a list of different news, which i want to show in a tableView. However in order to make it effective i wan't to make some kind of pagination, so that not all objects is loaded into the tableView. This i've achieved through simple variables like
let pageSize = 20
var lastLoadedPage = 0
however how do i make sure that the database in my case realm.io always is up to date with all the news from the api. I can easily change the api and add more parameters if it makes this easier? What is best practice? i'm using Alamofire and realm.io
Realm itself doesn't actually require pagination. The data is saved straight to disk, and then only the properties that are required are lazily paged in as they are called. As such, it's very memory-efficient, so much to the point where managing blocks of objects in memory (like pagination works) isn't necessary.
If you want to 'simulate' pagination with Realm, it's simply a matter of querying for all of the objects as a List, and then pulling out a sub-set of the objects you wish to display.
That all being said, it's probably still wise to paginate your calls to the web API so you don't needlessly download more news items than you require, but once they're downloaded and saved to Realm, you won't need to worry about any similar device-side logic. :)

Using Breeze for arbitrary server response

Have all a structure for creating complex queries and obtaining data on the client side using Breeze and webapi IQueryable<T>.
I would use this structure on the client side to call another webapi controller, intercept the result of the query, and use this to make an Excel file returned by HttpResponseMessage.
See: Returning binary file from controller in ASP.NET Web API
How can I use the executeQuery without getting return data in standard Breeze JSON and without interfering with the data on the client side cache to have the 'octet-stream'.
The goal is to create an 'Export to Excel' without existing frontend paging for a large volume of data.
If you don't want to track changes, call EntityQuery.noTracking() before calling executeQuery(). This will return raw javascript objects without breeze tracking capabilities.
You can't make executeQuery() return binary 'octet-stream' data. But you can use breeze ajax implementation:
var ajaxImpl = breeze.config.getAdapterInstance("ajax");
ajaxImpl.ajax() // by default it is a wrapper to jQuery.ajax
Look http://www.breezejs.com/documentation/customizing-ajax
Create a custom "data service adapter" and specify it when you create an EntityManager for this special purpose. It can be quite simple because you disable the most difficult parts to implement, the metadata and saveChanges methods.
You don't want to cache the results. Therefore, you make sure the manager's metadata store is empty and you should add the " no caching" QueryOption. [exact names escape me as I write this on my phone].
Make sure these steps are really adding tangible value
Specialized server operations often can be performed more simply with native AJAX components.
p.s. I just saw #didar 's answer which is consistent with mine. Blend these thoughts into your solution.

Store data between action

What the best way to store data between two controller action?
Example:
I have a big array of posts id ["2907", "2334", "2309",.... N] i create it in first step confirm and go to second step to another controller action.
Another controller action render data (calendar, groups), i select date in calendar, choose group and create one more array of date-time data confirm and go to another action
Another action manipulate with this array and array of posts id, and render date again the data what i whant to save after confirm, data safe in DB and clear all array from session.
I store all array between action in session like session[:posts_ids] = params[:posts_ids] and flash[:date_day] ||= params[:date_day]. I think it do not work for a really big data array. May be the best way store it in redis ?
This is largely opinion-based, but I think your two best options are:
Use Redis, Memcached or some other server-side cacheing solution to store the objects in memory until you need them.
Make your app more ajax-y and do all of the selection and temporary
persistence of those arrays client-side.
Session size is limited by the underlying strategy, rather than a hard limit for sessions in general. CookieStore is the default and will allow ~4k of data, because browser cookies are limited to that size. If you use database-backed sessions, you're only limited by your database server.
You should also keep in mind that using sessions to store data between requests isn't very RESTful.

Is it acceptable to have a single instance of a model to keep "global", alterable information?

I ran into a problem which required me to have access to a bunch of variables which need to be changed every so often, so I made a Misc model and there is only ever one instance of it. This was my solution for having editable global variables.
It holds all types of stuff that didn't seem like they deserve their own models. Is this acceptable or does this violate some Rails-buliding principle I'm not aware of? It works, but I have doubts.
Is there a better alternative to this strategy (think fetching/editing (as an example) Misc.first.todays_specials).
If this is passable, then is there a way to prevent a creation of more than one item of a model in the database? The problem with the above approach as you can see is that if there are all of a sudden TWO entries for Misc, things will get wonky as it requests the .first under the assumption that there's ever only going to be one.
You can create a table for Settings storing key-value configs. It will be scalable and not depend on predefined keys. Also you won't have a table with one row this way.
If you need lots of read/writes you might also want to cache rails SQL Caching
you could use a singleton pattern.
a singleton class is a class that can only have one instance.
so you could do something like this:
initializers/config.rb
require 'singleton'
class MyConfig
include Singleton
attr_accessor :config1
def initialize
self.config1 = ["hello", "world"]
end
end
and use it in this way:
MyConfig.instance.config1
You can also consider global variables. Global variables are those which start with the $ sign, and are accessible in the whola application by all instances of your ws.
Using a singleton to hold global state is a very bad idea, especially in a web-server:
If you are using a multi-threaded environment - you will run into thread-safety issues.
More relevantly - if you run multi-process, or multi-server (as you would have to, if your web application ever succeeds...) - the state will be inconsistent, as changes in one process/machine will not be propagated to the other processes/machines.
A restart of your application will destroy the state of the application, since it is held only in memory.
You could use an SQL solution, as suggested by #Tala, but if you want something more light-weight and 'freestyle', you might want to look at some key-value stores like memcached or redis, where you could save your state in a central location, and fetch it when needed.

Difference between findAll, getAll and list in Grails

With Grails there are several ways to do the same thing.
Finds all of domain class instances:
Book.findAll()
Book.getAll()
Book.list()
Retrieves an instance of the domain class for the specified id:
Book.findById(1)
Book.get(1)
When do you use each one? Are there significant differences in performance?
getAll is an enhanced version of get that takes multiple ids and returns a List of instances. The list size will be the same as the number of provided ids; any misses will result in a null at that slot. See http://grails.org/doc/latest/ref/Domain%20Classes/getAll.html
findAll lets you use HQL queries and supports pagination, but they're not limited to instances of the calling class so I use executeQuery instead. See http://grails.org/doc/latest/ref/Domain%20Classes/findAll.html
list finds all instances and supports pagination. See http://grails.org/doc/latest/ref/Domain%20Classes/list.html
get retrieves a single instance by id. It uses the instance cache, so multiple calls within the same Hibernate session will result in at most one database call (e.g. if the instance is in the 2nd-level cache and you've enabled it).
findById is a dynamic finder, like findByName, findByFoo, etc. As such it does not use the instance cache, but can be cached if you have query caching enabled (typically not a good idea). get should be preferred since its caching is a lot smarter; cached query results (even for a single instance like this) are pessimistically cleared more often than you would expect, but the instance cache doesn't need to be so pessimistic.
The one use case I would have for findById is as a security-related check, combined with another property. For example instead of retrieving a CreditCard instance using CreditCard.get(cardId), I'd find the currently logged-in user and use CreditCard.findByIdAndUser(cardId, user). This assumes that CreditCard has a User user property. That way both properties have to match, and this would block a hacker from accessing the card instance since the card id might match, but the user wouldn't.
Another difference between Domain.findByID(id) and Domain.get(id) is that if you're using a hibernate filter, you need to use Domain.findById(id). Domain.get(id) bypasses the filter.
AFAIK, these are all identical
Book.findAll()
Book.getAll()
Book.list()
These will return the same results
Book.findById(1)
Book.get(1)
but get(id) will use the cache (if enabled), so should be preferred to findById(1)

Resources