Simpler Way to Add a new Field to Object in Rails - ruby-on-rails

I have a field in animal_food (a json object) called treats and I want to add a field in treats called time_eaten and then return everything from the field treats.
def addTime(time)
animal_food["treats"]["time_eaten"] = time
animal_food["treats"]
end
Is there a way I can do the code above in 1 line (using merge or other ruby syntax?)

Yes:
animal_food['treats'].merge!({'time_eaten' => time})
does the same thing as those two lines. (Note the exclamation mark.) You could also say
animal_food['treats'].tap { |treats| treats['time_eaten'] = time }
Or, in Ruby 2.7 preview, using numbered parameters:
animal_food['treats'].tap { #1['time_eaten'] = time }

Related

0 Checking if TextBox.Text contains the string in the table. But it doesn't work? Lua

I am making a script inside TextButton script that will check if the TextBox contains any of the word or string inside the table.
text = script.Parent.Parent:WaitForChild('TextBox')
label = script.Parent.Parent:WaitForChild('TextLabel')
a = {'test1','test2','test3'}
script.Parent.MouseButton1Click:connect(function()
if string.match(text.Text, a) then
label.Text = "The word "..text.Text.." was found in the table."
else
label.Text = "The word "..text.Text.." was not found in the table."
end
end)
But it gives an error string expected, got table. from line 7 which is refering to the line if string.match....
Is there any way to get all text in the table?
What's the right way to do it?
Oh boy, there's a lot to say about this.
The error message
Yes.
No, seriously, the answer is yes. The error message is exactly right. a is a table value; you can clearly see that on the third line of code. string.match needs a string as its second argument, so it obviously crashes.
Simple solution
use a for loop and check for each string in a separately.
found = false
for index, entry in ipairs(a) do
if entry == text.Text then
found = true
end
end
if found then
... -- the rest of your code
The better* solution
In Lua, if we want to know if a single element is in a set, we usually take advantage of the fact that tables are implemented as hashmaps, meaning they are very fast when looking up keys.
For that to work, one first needs to change the way the table looks:
a = {["test1"] = true, ["test2"] = true, ["test3"] = true}
Then we can just index a with a string to find out if it is contained int eh set.
if a[text.Text] then ...
* In practice this is just as good as the first solution as long as you only have a few elements in your table. It only becomes relevant when you have a few hundred entries or your code needs to run absolutely as fast as possible.

LUA : Use table from another file

I just studied Lua language. I am very confused about it.
I have two file
string.lua
STRINGS=
{
CHARACTER_NAMES =
{
web = "webby",
sac = "sacso",
}
}
STRINGS.BUNNYNAMES =
{
"Brassica",
"Bunium",
"Burdock",
"Carrot",
}
And I have generate.lua file for get value form table in string.lua.
Then print value.
But I don't know how to acess table form another file.
I want to use STRINGS and STRINGS.BUNNYNAMES too,
Please advise me.
string.lua defines one global variable named STRINGS which contains a table.
You need to execute string.lua before you can access STRINGS. Just do dofile("string.lua") for instance.

Ruby on Rails statement executed on an array check if subelement string is unique

I have an array objects, for this example lets call it Diff. These diffs have multiple fields that are not all the same (old_image, new_image, url, etc). new_image and old_image in this case have fields on them, most importantly a field called image_file_name.
I want to get an array of all the diffs with an unique old_image.image_file_name i.e. no diff should have an old_image with the same file name.
I believe the logic should look something like this.
unique_diffs = Array.new
#diff.build.diffs.each { |diff|
if diff.old_image.image_file_name != #diff.old_image.image_file_name
unique_diffs.push(diff)
end
}
Or something like this
#unique_diffs = #diff.build.diffs.map{|diff| diff.old_image.image_file_name}.uniq
Any help would be much appreciated.
Try something like this:
Diff = Struct.new(:old_image)
Image = Struct.new(:image_file_name)
diffs = [
Diff.new(Image.new('name1')),
Diff.new(Image.new('name2')),
Diff.new(nil),
Diff.new(Image.new('name1')),
]
uniqs = diffs.select { |diff| diff.old_image }.uniq { |diff| diff.old_image.image_file_name }
p uniqs # prints Diff with name1 and Diff with name 2
The only important line is the one that calls select and uniq.
You need to use select to leave only the diffs with the old image, and then use uniq to drop those with the duplicated image file names.
I ended up using the loop, I was hoping to make this cleaner with the uniq function but it didn't seem to work, it gave me back all the diffs instead of the ones with the unique old image filename.
#diff.build.diffs.each { |diff|
if diff.old_image.image_file_name == #diff.old_image.image_file_name
# Logic went here
end
}
Still open to improving this but for now this will have to do.

AutoIncrement fields other than Id in grails

I'm new to Grails. I have a field in my domain object which I define as an String.
String ponum
When i click first time on create page ,the "ponum" field has to display 0001 and later it has to save in database.And When i click on second time the "ponum" field has to display 0002 and later it has to save in database.Everytime i click on create page "ponum" field has to autoincrement and save it database.I google ,but i did not get any document.
thanks
As things get an id anyway (assuming your using a regular rdbms with standard id genaerator), why not just pretend there's a variable ponum which is based on the id?
Just add a getter to your domain class:
class Page {
String getPonum() {
String.format( "%04d", id )
}
}
According to this answer, it is not possible to use hibernate generators (those used for ids) to do that. If you really need to use Hibernate generators, a workaround is described in the answer as well.
In your case, you could use an interceptor to generator your ponum property when inserting a new object:
class Yours {
int ponum
def beforeInsert() {
def lastPonum = Book.list([sort: 'ponum', order:'desc', max: 1])
if(lastPonum)
ponum = (lastPonum.pop().ponum as int) + 1 as String
else
ponum = '0'
}
}

Nokogiri/Ruby array question

I have a quick question. I am currently writing a Nokogiri/Ruby script and have the following code:
fullId = doc.xpath("/success/data/annotatorResultBean/annotations/annotationBean/concept/fullId")
fullId.each do |e|
e = e.to_s()
g.write(e + "\n")
end
This spits out the following text:
<fullId>D001792</fullId>
<fullId>D001792</fullId>
<fullId>D001792</fullId>
<fullId>D008715</fullId>
I wanted the just the numbers text in between the "< fullid>" saved, without the < fullId>,< /fullId> markup. What am I missing?
Bobby
I think you want to use the text() accessor (which returns the child text values), rather than to_s() (which serializes the entire node, as you see here).
I'm not sure what the g object you're calling write on is, but the following code should give you an array containing all of the text in the fullId nodes:
doc.xpath(your_xpath).map {|e| e.text}

Resources