Rails: saving a string on an object -- syntax problem? - ruby-on-rails

I am trying to write a simple function to clean a filename string and update the object. When I save a test string it works, but when I try to save the string variable I've created, nothing happens. But when I return the string, the output seems to be correct! What am I missing?
def clean_filename
clean_name = filename
clean_name.gsub! /^.*(\\|\/)/, ''
clean_name.gsub! /[^A-Za-z0-9\.\-]/, '_'
clean_name.gsub!(/\_+/, ' ')
#update_attribute(:filename, "test") #<-- correctly sets filename to test
#update_attribute(:filename, clean_name) #<-- no effect????? WTF
#return clean_name <-- seems to returns the correct string
end
Thank you very much.

Is the update only going through if the object ID has changed? I think it is reasonable to update the slot only when the object itself has changed.
Have you ever tried to use gsub instead of gsub!, so that the object ID changes?

Related

string.len() always returns the error "unexpected symbol"

function Main(Inhalt)
print(string.len(Inhalt))
end
Main(Bla)
This is just a example, I run in multiple problems like: "input:3: bad argument #1 to 'len' (string expected, got nil)" (Like here), or anything else with unexpected.
I'm kinda new to this, so please explain it to me from ground up I'm trying to figure out for a pretty long time. I already tried to convert this to a string with tostring(), but yes I'm missing something. Thanks for your help.
In this case Bla either needs to be a string which you can fix by putting quotes around it
function Main(Inhalt)
print(string.len(Inhalt))
end
Main("Bla")
or needs to be a variable that contains a string
Bla="test string"
function Main(Inhalt)
print(string.len(Inhalt))
end
Main(Bla)
Not a lua expert but it seems like you're trying to get the length of the string value Bla. The way you've written it right now does not indicate Bla is of string type. If you change it to the following, this should work.
function Main(Inhalt)
print(string.len(Inhalt))
end
Main("Bla")
Try this:
string1 = "Bla"
Main(string1)
In your code snippet Bla is not defined. Strings are surrounded by "".

Value stored in a variable is different than what is returned by the right hand side of '='

If I execute
env['rack.request.cookie_string'].split('\; ')
I get the expected result (array of strings). I have a line of code like this in my controller action:
foo = env['rack.request.cookie_string'].split('\; ')
When I stop with byebug just after that line, foo contains the entire cookie string env['rack.request.cookie_string']. What is going on?
Problem solved. I had to use split("\; ") instead of split('\; ').

How can I do about " and ' for saved object in server side and use it for JSON.parse() in javascript?

How can I do about " and ' for saving object and use it for JSON.parse() in javascript?
Because I have some strings and user can type using " and ' in a single string, for example "some description like "abc" for '3 feet" or "about 3'5 feet" or "wel"come"". When I want to transform into a JSON, especially when I want to parse in view side, for example:
var test = '${test as JSON}';
It breaks because contains escape like \"
However, if only contains " and use this JSON.parse("[{"abc": "asda"das"}]"), still invalid, because need escape.
So, I really don't know what I should do in thoses cases. I need some explanation how to fix, avoid or magic.
JSON can be treated directly as Object in Javascript. So you can simply write:
var test = ${(test as JSON).toString()}
Optionally, you can pass true to the toString() method to make the JSON pretty string or Object.
var test = ${(test as JSON).toString(true)}

Cannot access params map using Groovy

I want little help which I suspect is due to my lack of understanding for Groovy syntax. So, here's the thing:
On the GSP page I want to set a field's value from the params map which is
["id":"107901", "Field_10.value":"2", "Field_10":["value":"2"],"Field_11.value":"", "Field_11":["value":""],action:'abc']
On the gsp page, I want to find the value against the key Field_{some-id}.value
So I am calling a tag like, g.testTag(id:field.id) with its implementation as
def testTag = { attrs,body->
println "params are ${params}"
def result = ""
def keyRequired = "Field_${attrs.id}.value"
println "keyRequired >>>>> ${keyRequired.toString()}"
params.each { key,value->
println "key is ${key}"
println "Value is ${value}"
if (key.equals(keyRequired.toString())) {
result = params.value
}
}
println "Final result is >>>>>> ${result}"
}
The value passed in id is 10 and with my params printed as above, I was expecting a value
of 2 which is corresponding to the key in the params to show up. But apparently I see the
result as null..
What am I doing wrong ? Can anyone help please...
Thanks
Not result = params.value, but result = value.
You have to change the line:
result = params.value
to:
result = value
At the each loop, you're basically saying that inside the params iteration, you're naming every key "key" and every value "value". So, params.value will actually look for the key value inside your params map, which is null.
Funny that you do that right with key but not with value. Probably just got distracted.
it is likely what you want to do, the groovy way (no need to loop over the keys of the map) to access "Field_10.value":"2"
result=params["Field_${attrs.id}.value"]
Alternatively, this also works because you have "Field_10":["value":"2"] in your map
result=params["Field_${attrs.id}"].value

Rails 3: object.save is writing the old values to database

I have code which is updating a model's property then calling save!. A Rails.logger.info call shows that the model thinks it has the new values. But the SQL write performed by the save! call is writing the old value to the database.
At first it wasn't writing anything to the database at all when I called save!. I thought it was that the object wasn't thinking its value had changed for some reason: changed? returned false, so I used a _will_change! notification to force a write. But now it is doing a write, but with the old values.
This doesn't happen from the "rails console" command line: there I'm able to update the property and it will return changed? of true, and let me save successfully.
Excerpt from the server log follows. Note that the object thinks it has log_ids of '1234,5678,1137', but writes to the database '1234,5678'.
current log ids are [1234, 5678]
new log ids are [1234, 5678, 1137]; writing log_ids of '1234,5678,1137' to NewsList 13 with dirty true
SQL (2.0ms) UPDATE "news_lists" SET "log_ids" = '1234,5678', "updated_at" = '2012-01-02 02:12:17.612283' WHERE ("news_lists"."id" = 13)
The object property in question is log_ids, which is a string containing several IDs of another kind of object.
The source code that produced the output above:
def add_log(new_log)
new_ids = get_log_ids
Rails.logger.info("current log ids are #{new_ids}")
if new_ids.length >= NewsList.MAX_LENGTH
new_ids.shift
end
log_ids_will_change!
new_ids.push new_log.id
log_ids = new_ids.join ","
Rails.logger.info("new log ids are #{new_ids}; writing log_ids of '#{log_ids}' to NewsList #{id} with dirty #{changed?}")
save!
end
def get_log_ids
if log_ids
log_ids.split(",").map &:to_i
else
[]
end
end
Can anyone suggest what might be going on here?
Add the self to self.log_ids = new_ids.join "," otherwise you will just be assigning to the local variable (namesake) instead of the db-persisted attribute (column).

Resources