orientação a objetos – Como atribuir no construtor de uma classe filha uma instância da classe pai em Ruby

Eu tenho uma classe filha que é inicializada com algumas instâncias:

def initialize(nome:, preco:, categoria:)
    @nome = nome
    @preco = preco
    @categoria = categoria
end

Mas preciso que a variável @categoria seja puxada do construtor da classe pai. A instância que preciso da classe pai está com outro nome e não consegui pegar utilizando o método super.

  def initialize(nome: 'Geral')
    @nome = nome
  end

Em resumo, preciso que o atributo @categoria da classe filha herde o atributo @nome da classe pai.

Duvida Automação RUBY – page object – instancia

Na automação, sempre ao abrir o Browser pela primeira vez, abre aquelas “telas de segurança” informando que o site não é seguro e precisa clicar em “avançar mesmo assim” para entrar na url.

Um detalhe: Isso só ocorre na primeira vez que entra na url (testes manuais) e se a automação tiver vários cenários feitos em seguida, só aparece a primeira vez, as demais não aparece a tela.

É possível programar um SE para essa situação?
Ou seja, caso apareça essa tela faça e caso não apareça faz esse outro?

Idiomatic Ruby if/else in a Sinatra route

Apologies if this question doesn’t fit the format here, seemed more appropriate here than SO due to the more nebulous nature of the question.

Think mini tinyURL clone: POST to service to save the url + hash, then look up the mapping when visiting /anything. It’s been a while since I’ve touched Ruby, and the resulting code snippet is not easy on the eyes:

require 'sinatra'
require 'mongoid'
require 'digest'

class MinifiedUrl
  include Mongoid::Document

  field :code, type: String
  field :original_url, type: String
end

# Redirect to the actual url, like tinyurl.com/abcdefg
get '/:code' do
  link = MinifiedUrl.where(:code => params(:code)).first # .first is falsy if there is no mapping
  if link
    puts "Found minified link"
    redirect link(:original_url), 302
  else
    puts "No minified link"
    redirect '/404', 404
  end
end

# Create a mapping from a POST request like { url: 'https://google.com/ '}
post '/' do
  incoming_url = params(:url)

  link = MinifiedUrl.where(:code => params(:code)).first 
  # Reassign link if link is falsy
  link = MinifiedUrl.create(:target_url => incoming_url, :code => Digest::MD5.hexdigest(incoming_url)(0..5)) unless link

  link(:slug)
end

Is there an obvious way to make the code more idiomatic? My concern is multiple calls to MinifiedUrl model / reassigning value of link. I can’t put my finger on it, but it doesn’t feel ruby-like.

Idiomatic Ruby if/else in a Sinatra route

Apologies if this question doesn’t fit the format here, seemed more appropriate here than SO due to the more nebulous nature of the question.

Think mini tinyURL clone: POST to service to save the url + hash, then look up the mapping when visiting /anything. It’s been a while since I’ve touched Ruby, and the resulting code snippet is not easy on the eyes:

require 'sinatra'
require 'mongoid'
require 'digest'

class MinifiedUrl
  include Mongoid::Document

  field :code, type: String
  field :original_url, type: String
end

# Redirect to the actual url, like tinyurl.com/abcdefg
get '/:code' do
  link = MinifiedUrl.where(:code => params(:code)).first # .first is falsy if there is no mapping
  if link
    puts "Found minified link"
    redirect link(:original_url), 302
  else
    puts "No minified link"
    redirect '/404', 404
  end
end

# Create a mapping from a POST request like { url: 'https://google.com/ '}
post '/' do
  incoming_url = params(:url)

  link = MinifiedUrl.where(:code => params(:code)).first 
  # Reassign link if link is falsy
  link = MinifiedUrl.create(:target_url => incoming_url, :code => Digest::MD5.hexdigest(incoming_url)(0..5)) unless link

  link(:slug)
end

Is there an obvious way to make the code more idiomatic? My concern is multiple calls to MinifiedUrl model / reassigning value of link. I can’t put my finger on it, but it doesn’t feel ruby-like.

Make Ruby file executable in Windows 10

I’m trying to build Tic Tac Toe via Ruby, and I want Ruby file to be executable so everyone can run it.

The problem is: I’m using Windows 10, and I’m not able to make the file executable:

  • I’ve tried to make it executable using Right Click and via the Security tab
  • I’ve also tried following this guide but didn’t work.
  • When I’m putting #!/usr/bin/env ruby at the top of the file, Rubocop is throwing error telling me that this file is not executable

I’ve searched everywhere, but couldn’t find a solution. I would be thankful if you can help me solve this problem.

Is Ruby on Rails a waste of time? ( Bay Area)

I’m learning we are using Ruby on Rails on the backend/server, PostgresSQL to house our database, and JavaScript + React + Redux for frontend rendering and logic. Through App Academy’s free online course. Its been REALLY helpful in teaching me the foundations of coding and software engineering. I’ve done some research and found out that Ruby on Rails is a dying language. I love this program, and I’m learning so much but I’m worried I won’t be a competitive candidate in the tech industry with Ruby on Rails. Can anyone give me some insight into what the job market is gonna be like for a Ruby on Rails developer in the Bay Area (Silicon Valley)?
Any insight is valuable.

ruby on rails – Nested attributes, column calculations, and where statement

I am not getting the output I am looking for seems like I might be calling my variable incorrectly

Here is my controller variable for @vendor
@vendors = User.inlcudes(line_items: ({ sale: :skiswap})).where(sales: {skiswap_id: @skiswap.id})

then have

      <% @vendors.each do |vendor| %>
      <tr class="group border-t border-gray-400 hover:bg-gray-100">
        <td class="p-3"><%= vendor.company %></td>
        <td class="p-3"><%= vendor.name  %></td>
        <td class="p-3"><%= vendor.email%></td>
        <td class="p-3"><%= number_to_phone(vendor.phone_number, area_code: true)%></td>
        <td class="p-3"><%= vendor.line_items.sum(:total_price)%></td>
      <% end %>

The line
<td class="p-3"><%= vendor.line_items.sum(:total_price)%></td>
is not using the original where statement, so my total is incorrect.

the server output lines shows this

  SQL (1.7ms)  SELECT "users"."id" AS t0_r0, "users"."email" AS t0_r1, "users"."encrypted_password" AS t0_r2, "users"."reset_password_token" AS t0_r3, "users"."reset_password_sent_at" AS t0_r4, "users"."remember_created_at" AS t0_r5, "users"."confirmation_token" AS t0_r6, "users"."confirmed_at" AS t0_r7, "users"."confirmation_sent_at" AS t0_r8, "users"."unconfirmed_email" AS t0_r9, "users"."first_name" AS t0_r10, "users"."last_name" AS t0_r11, "users"."time_zone" AS t0_r12, "users"."accepted_terms_at" AS t0_r13, "users"."accepted_privacy_at" AS t0_r14, "users"."announcements_read_at" AS t0_r15, "users"."admin" AS t0_r16, "users"."created_at" AS t0_r17, "users"."updated_at" AS t0_r18, "users"."invitation_token" AS t0_r19, "users"."invitation_created_at" AS t0_r20, "users"."invitation_sent_at" AS t0_r21, "users"."invitation_accepted_at" AS t0_r22, "users"."invitation_limit" AS t0_r23, "users"."invited_by_type" AS t0_r24, "users"."invited_by_id" AS t0_r25, "users"."invitations_count" AS t0_r26, "users"."company" AS t0_r27, "users"."phone_number" AS t0_r28, "line_items"."id" AS t1_r0, "line_items"."quantity" AS t1_r1, "line_items"."price" AS t1_r2, "line_items"."total_price" AS t1_r3, "line_items"."created_at" AS t1_r4, "line_items"."updated_at" AS t1_r5, "line_items"."consigner_type" AS t1_r6, "line_items"."consigner_amount" AS t1_r7, "line_items"."skiswap_take" AS t1_r8, "line_items"."sale_id" AS t1_r9, "line_items"."tag" AS t1_r10, "line_items"."inventory_id" AS t1_r11, "sales"."id" AS t2_r0, "sales"."amount" AS t2_r1, "sales"."total_amount" AS t2_r2, "sales"."tax" AS t2_r3, "sales"."vendor_payout" AS t2_r4, "sales"."public_payout" AS t2_r5, "sales"."comments" AS t2_r6, "sales"."skiswap_id" AS t2_r7, "sales"."created_at" AS t2_r8, "sales"."updated_at" AS t2_r9, "sales"."remaining_balance" AS t2_r10, "sales"."complete" AS t2_r11, "sales"."void" AS t2_r12, "skiswaps"."id" AS t3_r0, "skiswaps"."swap_name" AS t3_r1, "skiswaps"."user_id" AS t3_r2, "skiswaps"."description" AS t3_r3, "skiswaps"."vendor_precentage" AS t3_r4, "skiswaps"."website" AS t3_r5, "skiswaps"."contact_name" AS t3_r6, "skiswaps"."contact_email" AS t3_r7, "skiswaps"."contact_number" AS t3_r8, "skiswaps"."created_at" AS t3_r9, "skiswaps"."updated_at" AS t3_r10, "skiswaps"."event_address" AS t3_r11, "skiswaps"."state" AS t3_r12, "skiswaps"."city" AS t3_r13, "skiswaps"."zip" AS t3_r14, "skiswaps"."public_precentage" AS t3_r15, "skiswaps"."tax" AS t3_r16 FROM "users" LEFT OUTER JOIN "inventories" ON "inventories"."user_id" = "users"."id" LEFT OUTER JOIN "line_items" ON "line_items"."inventory_id" = "inventories"."id" LEFT OUTER JOIN "sales" ON "sales"."id" = "line_items"."sale_id" LEFT OUTER JOIN "skiswaps" ON "skiswaps"."id" = "sales"."skiswap_id" WHERE "sales"."skiswap_id" = $1  (("skiswap_id", 3))
  ↳ app/views/pos_dashboard/index.html.erb:40
   (0.6ms)  SELECT SUM("line_items"."total_price") FROM "line_items" INNER JOIN "inventories" ON "line_items"."inventory_id" = "inventories"."id" WHERE "inventories"."user_id" = $1  (("user_id", 3))
  ↳ app/views/pos_dashboard/index.html.erb:46
  CACHE  (0.0ms)  SELECT SUM("line_items"."total_price") FROM "line_items" INNER JOIN "inventories" ON "line_items"."inventory_id" = "inventories"."id" WHERE "inventories"."user_id" = $1  (("user_id", 1))

The total amount is accurate for the Users total_price but not for total_price within that swap…

Any help would be great

sql – Filter a database table in Ruby, migrating code to Postgres

# Users

| id    | name     | age  |
| ----- | -------- | ---- |
| 1     | Rand     | 25   |
| 2     | Mat      | 24   |
| 3     | Perrin   | 23   |

Given the above table I’ve been building queries against it in Rails with the basic stuff which works quite well. The real application has about 10 of those fields to query against.

users = User.none
users = users.where(age: params(:age))   if params(:age)
users = users.where(name: params(:name)) if params(:name)

I’ve always wanted to try to move that into the database and I came up with this function in Postgres

CREATE OR REPLACE FUNCTION filter_users(name character varying, age integer)
RETURNS TABLE(
  user_id int,
  name character varying,
  age integer
)
AS $$

select id as user_id, name, age
from users
where 1 = 1
  and (name IS NULL OR name = $1)
  and (age IS NULL OR age = $2)

$$ LANGUAGE SQL;

What I would like to know is whether there is a better way to do these multiple where queries, where each of them can be null, and should therefore not be used?

Como eu posso fazer uma autenticação de rotas com JWT em Ruby on Rails?

Eu estou tentando implementar uma autenticação utilizando JWT sem o devise e eu consigo gerar um token de autenticação, porem quando eu tento autenticar rotas ele me retorna um erro:

Couldn’t find all Users with ‘XXXX’: ({“user_id”=>(“XXX”, “XXX”), “exp”=>1600470434}, {“alg”=>”HS256”}) (found 0 results, but was looking for 1)

Apontando o erro para esse código no exatamente na linha 18:

inserir a descrição da imagem aqui

Alguem pode me dizer uma solução?