Validating array insertion in Rails - arrays

I have Table1 with attribute attribute1, which is an array of integer. My controller allows for one insertion at a time. So, in the controller:
def add_attribute1_item
table1 = Table1.find(params[:id])
table1.attribute1 << add_params[:attribute1_item]
table1.save!
render json: table1
rescue
render_errors_for(table1)
end
I want to validate this attribute1_item value, ignoring the old values that have been stored in attribute1 array, e.g. if table1.attribute1 contains 99 and I call the controller add_attribute1_item to add 100, I only want to check whether 100 is valid or not, ignoring 99.
class Task < ApplicationRecord
.
.
.
validate :attribute1_item_is_valid, if: -> { attribute1.present? }
.
.
.
def attribute1_item_is_valid
# validate the item by accessing attribute1
end
I am unsure with this approach because when I access attribute1 in attribute1_item_is_valid, it is the whole array instead of the new item. Is this approach good enough by calling attribute1.last() or is there a more correct method?
thank you

Instead of trying to validate this in the model, validate the form entry.
Create a model for the form and use normal validations.
class SomeForm
include ActiveModel::Model
attr_accessor :id, :attribute1_item
validate :id, presence: true, numericality: { only_integer: true }
validate :attribute1_item, presence: true
end
def add_attribute1_item
form = SomeForm.new(params)
if form.invalid?
# render form.errors
return
end
table1 = Table1.find(form.id)
table1.attribute1 << form.attribute1_item
table1.save!
render json: table1
rescue
render_errors_for(table1)
end

Related

Ruby how to print/puts read file contents instead of a bunch of numbers/symbols

In ruby I have created a class and array, to read the contents from a text file then output them.
class Album
attr_accessor :artist, :title, :genre, :tracks
end
album = Album.new(album_title, album_artist, album_genre, tracks)
-> tracks is an array of multiple lines read from the text file using a while loop. Context below, a_file/music_file File.new("album.txt", "r")
class Track
attr_accessor :name, :location
def read_track(a_file)
track_title = a_file.gets()
track_location = a_file.gets()
track = Track.new(track_title, track_location)
end
def read_tracks(music_file)
tracks = Array.new()
count = music_file.gets().to_i()
track = music_file
index = 0
while (index < count)
track = read_track(music_file)
tracks << track
index += 1
end
return tracks
end
end
after album = Album.new(album_title, album_artist, album_genre, tracks), I passed the album to a different procedure print_tracks(album), and in print_tracks(album), I have puts album.tracks.
But instead of printing out several lines of track names and track locations, I get something that looks like this:
#<Track:0x000055c028027b08>
#<Track:0x000055c0280277c0>
#<Track:0x000055c028027630>
How do I print out the actual words on the file?
What you are getting in return are instances of your Track class. Each of those instances has access to attributes like name and location as specified under the class definition in attr_accessor. You can change your last statement (return tracks) (take note that return here is not needed since its the last statement in the method, the last thing will be returned by default in ruby).
Try this instead of return tracks
tracks.map{ |track| {track_name: track.name, track_location: track.location} }
This was you will end up with array of hashes with keys of track_name and track_location each containing a value of one track. I am not sure what kind of format you want to return, but this is a rather simple, yet flexible. The most simplistic way would be array of array, which you can get using:
racks.map{ |track| [track.name, track.location] }
You're observing the default behavior defined in Object#to_s and Object#inspect.
Ruby uses the to_s method to convert objects to strings and the inspect method to obtain string representations of objects suitable for debugging. By default, to_s and inspect are more or less the same thing. The only difference is inspect will also show the instance variables.
You can and should override these methods in your Track class. For example:
class Track
def to_s
"#{self.class.name} #{name} # {location}"
end
def inspect
"#<#{to_s}>"
end
end
track.to_s
puts track
# Track: name # /music/name.flac
track.inspect
p track
# #<Track: name # /music/name.flac>

Add a CALCULATED fields with if-else condition in Django model

How can i add a calculated field with if-else condition in Django model?
for instance,
def _get_total(self):
"Returns the Overall Backlog"
return self.Forecast - self.Actual_t
Overall_Backlog = property(_get_total)
here, i want to create Overall_Backlog with a condition like if (self.Forecast - self.Actual_t)<0 then 0 else (self.Forecast - self.Actual_t).
Please help!
Exactly like that:
#property
def Overall_Backlog(self):
"Returns the Overall Backlog"
val = self.Forecast - self.Actual_t
if val < 0:
return 0
return val
A disadvantage of using a property is however that the database does not know anything about properties and methods, and thus can not filter. An alternative to using properties is using .annotate(…) [Django-doc]:
from django.db.models import Value
from django.db.models.functions import Greatest
MyModel.objects.annotate(
overall_backlog=Greatest(F('Forecast') - F('Actual_t'), Value(0))
)
The MyModel objects that arise from this QuerySet will have an extra attribute .overall_backlog that is the maximum of Forecast - Actual_t and 0.

Implementing union type with graphql-ruby

I'm trying to implement a union type with graphql-ruby.
I followed the official documentation but got the error listed below.
Here is my current code.
module Types
class AudioClipType < Types::BaseObject
field :id, Int, null: false
field :duration, Int, null: false
end
end
module Types
class MovieClipType < Types::BaseObject
field :id, Int, null: false
field :previewURL, String, null: false
field :resolution, Int, null: false
end
end
module Types
class MediaItemType < Types::BaseUnion
possible_types Types::AudioClipType, Types::MovieClipType
def self.resolve_type(object, context)
if object.is_a?(AudioClip)
Types::AudioClipType
else
Types::MovieClipType
end
end
end
end
module Types
class PostType < Types::BaseObject
description 'Post'
field :id, Int, null: false
field :media_item, Types::MediaItemType, null: true
end
end
And here is the graphql query.
{
posts {
id
mediaItem {
__typename
... on AudioClip {
id
duration
}
... on MovieClip {
id
previewURL
resolution
}
}
}
}
When I send the query I got the following error.
Failed to implement Post.mediaItem, tried:
- `Types::PostType#media_item`, which did not exist
- `Post#media_item`, which did not exist
- Looking up hash key `:media_item` or `"media_item"` on `#<Post:0x007fb385769428>`, but it wasn't a Hash
To implement this field, define one of the methods above (and check for typos
Couldn't find any typo or anything.
Am I missing something??
You didn't define parent type (superclass of your union).
So add
class Types::BaseUnion < GraphQL::Schema::Union
end
Now your inheritance chain will consistent.

Ruby Array Search Method Not Working As Intended

I am having trouble making the search method that i wrote in my script to work. Here is the relevant code from the script:
$records = []
def xml_extractor(document)
document.xpath("//record").each do |record|
$records << {"id" => record.xpath('id').text,
"first_name" => record.xpath('first_name').text,
"last_name" => record.xpath('last_name').text,
"email" => record.xpath('email').text,
"gender" => record.xpath('gender').text,
"ip_address" => record.xpath('ip_address').text,
"send_date" => record.xpath('send_date').text,
"email_body" => record.xpath('email_body').text,
"email_title" => record.xpath('email_title').text}
puts record
end
puts "\nAll records loaded!"
end
def search_by_ip(ip)
record_to_return = $records.select {|k| k["ip_address"] == ip.to_s}
puts JSON.pretty_generate(record_to_return)
end
Basically my xml_extractor method works fine and it stores everything into the array using nokogiri. The xml file that is being implemented has a thousand records each having its own first_name, last_name etc. But the problem is when i try to implement the search_by_ip method on the array a "null" value is returned, when what the method should really be doing is returning the entire record that belongs to that specific ip address. Also, i realised that every time i implement the xml_extractor method, i.e. when an xml document is parsed in into the array, the contents arent really saved in rather they are only displayed for while the loop is going. Which might be why I get a "null" for my search methods. Let me know what you guys think though.
I wrote an example of how to use OO to obtain what you want.
I don't have your document so I simplified your document to a 2 dimensional array
In the method read switch the comment to work with your xml
Each method can be chained and does only what is required
They can all be tested separatly (here by p'ting them)
class Xml_extractor
attr_reader :document, :records
def initialize document
#document = document
#records = []
end
def read
# #document.xpath("//record").each do |record|
#document.each do |record|
#records << {id: record[0], ip_address: record[1]}
end
self # return self so that you can chain another method
end
def search_by_ip(ip)
#return first of an array if found, nil otherwise
# attention to use a hash key here to search, not a string
#records.select {|k| k[:ip_address] == ip.to_s}.first
end
end
document = [[0, "192.168.0.1"], [1, "192.168.0.2"]]
p Xml_extractor.new(document).read.records
# [{:id=>0, :ip_address=>"192.168.0.1"}, {:id=>1, :ip_address=>"192.168.0.2"}]
p Xml_extractor.new(document).read.search_by_ip("192.168.0.2")
# [{:id=>1, :ip_address=>"192.168.0.2"}]
p Xml_extractor.new(document).read.search_by_ip("192.168.0.2").to_json
# "[{\"id\":1,\"ip_address\":\"192.168.0.2\"}]"
In ruby your method will return the last line. If you want your method to return data, you need to return it on the last line. puts doesn't return anything.
Try to change like this:
def search_by_ip(ip)
record_to_return = $records.select {|k| k["ip_address"] == ip.to_s}
puts JSON.pretty_generate(record_to_return)
record_to_return
end

How to subclass an Array in Ruby?

I'm trying to subclass Array to implement a map method that returns instances of my Record class. I'm trying to create a sort of "lazy" array that only instantiates objects as they are needed to try and avoid allocating too many Ruby objects at once. I'm hoping to make better use of the garbage collector by only instantiating an object on each iteration.
class LazyArray < Array
def initialize(results)
#results = results
end
def map(&block)
record = Record.new(#results[i]) # how to get each item from #results for each iteration?
# how do I pass the record instance to the block for each iteration?
end
end
simple_array = [{name: 'foo'}, {name: 'bar'}]
lazy_array_instance = LazyArray.new(simple_array)
expect(lazy_array_instance).to be_an Array
expect(lazy_array_instance).to respond_to :map
lazy_array_instance.map do |record|
expect(record).to be_a Record
end
How can I subclass Array so that I can return an instance of my Record class in each iteration?
From what I know, you shouldn't have to do anything like this at all. Using .lazy you can perform lazy evaluation of arrays:
simple_array_of_results.lazy.map do |record|
# do something with Record instance
end
Now, you've got some odd situation where you're doing something like -
SomeOperation(simple_array_of_results)
and either you want SomeOperation to do it's thing lazily, or you want the output to be something lazy -
lazily_transformed_array_of_results = SomeOperation(simple_array_of_results)
page_of_results = lazily_transformed_array_of_results.take(10)
If that sounds right... I'd expect it to be as simple as:
SomeOperation(simple_array_of_results.lazy)
Does that work? array.lazy returns an object that responds to map, after all...
Edit:
...after reading your question again, it seems like what you actually want is something like:
SomeOperation(simple_array_of_results.lazy.collect{|r| SomeTransform(r)})
SomeTransform is whatever you're thinking of that takes that initial data and uses it to create your objects ("as needed" becoming "one at a time"). SomeOperation is whatever it is that needs to be passed something that responds to map.
So you have an array of simple attributes or some such and you want to instantiate an object before calling the map block. Sort of pre-processing on a value-by-value basis.
class Record
attr_accessor :name
def initialize(params={})
self.name = params[:name]
end
end
require 'delegate'
class MapEnhanced < SimpleDelegator
def map(&block)
#delegate_ds_obj.map do |attributes|
object = Record.new(attributes)
block.call(object)
end
end
end
array = MapEnhanced.new([{name: 'Joe'}, {name: 'Pete'}])
array.map {|record| record.name }
=> ["Joe" "Pete"]
An alternative (which will allow you to keep object.is_a? Array)
class MapEnhanced < Array
alias_method :old_map, :map
def map(&block)
old_map do |attributes|
object = Record.new(attributes)
block.call(object)
end
end
end

Resources