What's best way to make rails flash entries persist until the next action? - ruby-on-rails

I've put some code like this
flash[:task_loader] = flash[:task_loader]
flash[:task_loader_params] = flash[:task_loader_params]
in a function in my controller which all my actions can call. This has the effect of keeping those two flash entries in the FlashHash. (I presume this rather odd-looking code works because the '=' does more than just assign values.)
My question is, is there a better way to do this? Something like
flash[:task_loader].pin

Flash is a convenient wrapper for storing data in cookies and expiring them in the next request. So that your notification messages will work through 2 (or multiple) request response cycles.
If you want some more persistence, you can use session:
session[:task_loader] = my_task_loader
Note that one cookie can hold only 4KB of data.
(I presume odd-looking code works
because the '=' does more than just
assign values.)
This is because it is not simply an assignment, but a method []=, with a signature similar to this:
def []=(k, v)

Related

Lua variable variables

I'm very new to Lua, I'm working with it on an io controller which has strict limits on script sizes so I need to work within these limits.
I have a number of relays which I am controlling (1-64). I need to switch off a relay when an event happens, but the relay I'm switching off can change.
I have a variable that holds the relay number and I need to turn off this relay.
I can achieve this using I statements:
if variable = 1 then
io.relay1=0 //Turns off the relay
end
else if variable = 2 then
io.relay2=0 //Turns off the relay
end
However, this will very quickly become a large script when repeated for the 64 relays. Is it possible to address the relay using the value of the variable as the relay name? Similar to the below:
io.relay{variable}=0 //Turns off the relay1/2/3/4/5 etc. depending on the value of variable
Alternatively, is there another way to keep the code compact?
Use
io["relay".. variable]=0
However, this creates a string every time.
If you can change how io works, a better solution would be to make io.relay a table and then simply do io.relay[variable]=0.
To avoid the string allocation issue that lhf's answer has, you could pre-generate a string table and index into that:
relay_names = {}
for k = 1,64 do
relay_names[k] = "relay"..tostring(k)
end
Then setting the IO states would look something like this:
io[relay_names[1]] = 1

How to traverse an array in reverse direction in dust.js?

Is there any simple solution, or it can be accomplished only by defining a custom helper?
The best solution is probably to have the server send the array in reverse order to begin with. In most cases, the "Dust way" is to have the server send data in the format that it will be presented by Dust. If you don't have control over how the data is sent, though, you will either need a helper, or you can manipulate the data (using JavaScript) before passing it to dust.render.
var data = getData();
var data.arrayToReverse = reverseArray(data.arrayToReverse);
dust.render('myDustTemplate', data, function(err, out) {
// Show the result.
});
You would need to write the getData and reverseArray methods, but this way you could get the reversed array without a helper.

SWFAddress used to change INDIVIDUAL params in the url

I am using SWFAddress in actionscript 3 to control urls for navigation and controls, and while I am able to target and change specific parameters, I feel like I am missing a cleaner and more consistent way of handling it, perhaps even a feature or method I am not aware of.
Say I have a url and I want to change just the second param of def to xyz.
http://localhost/some-page/#/?param1=abc&param2=def&param3=ghi changed to
http://localhost/some-page/#/?param1=abc&param2=xyz&param3=ghi
I currently am doing:
if (SWFAddress.getParameterNames().indexOf("param2") >= 0) {
SWFAddress.setValue(SWFAddress.getPath() + "?"
+ SWFAddress.getQueryString().replace("param2=" + SWFAddress.getParameter("param2"), "param2=xyz"))
Essentially, checking if the param exists, checking what its current value is, then recreating the whole url using base, '?", and query, making sure I replace the the parameter and the parameter's value, making sure I don't miss the equal sign. This get's sloppy, and is error prone if the param exists but is not set to anything, or whether or not there is an equal sign, and a host of other pitfalls.
So, I can not just tell SWFAddress to update that one parameter in the url? A theoretical function of SWFAddress.setParam("param2, "xyz").
Has anyone coded their own method to micro-manipulate SWFAddress and the url, beyond the single function they supply you with of setValue(val:String)?
I think the short answer is no. According to the documentation there is no setParameter to go with the getParameter method. Looking at the code, it seems that the URL is not cached as a property in the class and therefore cannot be manipulated other than via the setValue method which, of course, updates the URL in the browser.
Presumably you're already parsing the URL in your onChange event so you can use the values to set your application state? If so, you shouldn't need to do so again when you come to rebuild the URL prior to updating it from Flash. If you store the deep-link properties on a Model class somewhere you can handle the defaulting, updating, and error checking without needing to resort to String manipulation. You would then rebuild the URL using those properties, a process you could abstract into a method in your Model class if required.
You should also note that the following line is not particularly robust since it will return true for properties such as param22 and sparam2:
if (SWFAddress.getParameterNames().indexOf("param2") >= 0) { }

Erlang and the records

What is wrong in this code?
I was expected "titi" in person.name but I still have "toto"!
More explicitly, how to modify a record in a function?
init1()->
S=#person{name="toto"}, %record creation and field setting
fct(S),
io:format("~s~n",[S#person.name]).
fct(R)->
R#person{name="titi"}. %record updating
You need to get a result of fct():
init1()->
S=#person{name="toto"}, %record creation and field setting
S2 = fct(S), % Get updated record
io:format("~s~n",[S2#person.name]).
fct(R)->
R#person{name="titi"}. %record updating
Bertaud, I think you are getting ahead of yourself a bit. You really need to understand the basics of immutability before you write any more code. (i.e. "variables" do not vary : you can only assign a value to them once.) I suggest you read the free online guide "Learn You Some Erlang For Great Good", at http://learnyousomeerlang.com/. The section that covers the basics of variables is http://learnyousomeerlang.com/starting-out-for-real#invariable-variables.
It is impossible to stress too much that all data in Erlang is immutable. So to do something like in your original question you need to modify it like #hdima did. The record is not updated but rewritten. In the same way there is no global data in Erlang, all data belongs to a process. This is even true of ETS tables as they basically behave like a process, albeit a built-in one without explicit communication.
So if you use the process dictionary or an ETS table the data itself can never be updated, only the dictionary/table. This means that to modify some data in the dictionary/table you basically have to:
"Read" the data
Update the data making new data
"Write" the new back into the dictionary/table
Without writing the new data back into the dictionary/table it will be lost, as your new data was.
Within fct(), you're not mutating the record, but you're returning a new value for the record, which needs to be used further. If you're calling fct(S), without handling the return value, then you'll lose that new value ("titi").

Does Rails have a per request store that I can add objects to and retrieve from?

In asp.net there is something called Request.Items that I can add an object to, and then I can check to see if an object is present in the .Items collection from another part of my code (like in another class).
Does Rails have something like this?
One of the most popular options is to use the request_store gem, which allows you to access a global store that you from any part of your code. It uses Thread.current to store your data, and takes care of cleaning up the data after each request.
RequestStore[:items] = []
Be aware though, since it uses Thread.current, it won't work properly in a multi-threaded environment where you have more than one thread per request.
To circumvent this problem, I have implemented a store that can be shared between threads for the same request. It's called request_store_rails, and the usage is very similar:
RequestLocals[:items] = []
You may define a class method (in any class you want) to store your data:
class Xyzzy
def self.items
#items ||= {}
end
end
# ....
if Xyzzy.items.include? :fubar
Xyzzy.items[:asd] = 1
end
But you should decide when you want this 'cache' to be cleared. If you want it only for one request, define a before_filter which will call Xyzzy.items.clear
The class objects are global. You may also use a standard global variable, but that would be less elegant. :)

Resources