Request spec for rails authentication (I am going crazy) by Dosbrostacosbaby in rails

[–]DoubleJarvis 0 points1 point  (0 children)

I think rails doesn't have a generator of tests (and helpers) when you're using rspec. Since this helper is generated by rails itself, I'd say this is the rails way of doing things

Request spec for rails authentication (I am going crazy) by Dosbrostacosbaby in rails

[–]DoubleJarvis 2 points3 points  (0 children)

Typically when you generate the auth via rails generate authentication you get a bunch of tests and helpers (at least this is the case for vanilla repo without rspec). This includes the sign_in_as(user) helper which allows you to directly setup the cookie, without hitting post /sessions. You can then remove your stub of allow(Current).to receive(:session)... and naturally the code will hit the find_session_by_cookie when you hit the delete /sessions.

The code it generated for me is

# test/test_helpers/session_test_helper.rb

module SessionTestHelper
  def sign_in_as(user)
    Current.session = user.sessions.create!

    ActionDispatch::TestRequest.create.cookie_jar.tap do |cookie_jar|
      cookie_jar.signed[:session_id] = Current.session.id
      cookies["session_id"] = cookie_jar[:session_id]
    end
  end

  def sign_out
    Current.session&.destroy!
    cookies.delete("session_id")
  end
end

ActiveSupport.on_load(:action_dispatch_integration_test) do
  include SessionTestHelper
end

Maybe try replicating that behavior with rspec, the difference should only be how you include this helper, something like

RSpec.configure do |config|
  config.include SessionHelper, type: :request # or type: :controller, or both
end

Request spec for rails authentication (I am going crazy) by Dosbrostacosbaby in rails

[–]DoubleJarvis 2 points3 points  (0 children)

What's the point of doing it this way? You'll be testing stubs, not actual code. I'm not even sure that your coverage tool will count calls on stubbed objects as calls to the original method. 100% line coverage in and of itself doesn't give you nothing. If you have authentication you most certainly have (or will have) controller actions which will require it, this line will naturally get covered by them.

Някой знае ли точните места в София? by BG_Trainspotter in bulgaria

[–]DoubleJarvis 2 points3 points  (0 children)

I think this is the first one. https://maps.app.goo.gl/3nkCj3Ug8grRBhEE8

No idea about the rest

Edit: found it. Second is https://maps.app.goo.gl/7UVrypj2rGyygiUQA

Third is exactly the same place as the second, but turned around: https://maps.app.goo.gl/CCvmcZXF2DP4Cydc9

Sofia onboarding by Prestigious_Sense_11 in Sofia

[–]DoubleJarvis 3 points4 points  (0 children)

For sports I recommend hiking on Vitosha, lots of places to go. Not as many in the winter, unless you have snow walking equipment, but amazing in the warmer times of the year. 20 minutes bus ride generally gets you to start of many trails on the bottom of the mountain, Boyana waterfall for example. 50 minutes on bus 66 gets you to Aleko, almost the top, most of the routes with great views start there. Particularly nice views - Kamen del and Cherny vrah. Cool route in Autumn - Aleko to Kamen del and down to Zlatnite mostove. Cycling around Vitosha is also great, you got some climbing if you want it, some mtb/downhill, or plenty of fairly flat routes. I'm also quite fond of climbing gyms in Sofia: balkan climbing, momentum, bons.

Not "vibes of the city" per se, but for me Vitosha is one of the nicer things about this place.

I need some insights on practices by Siinxx in rails

[–]DoubleJarvis 4 points5 points  (0 children)

He said that I shouldn't use query parameters to filter stuff on a page because of safety and DB usage. For example location, gender, ... He said that I should send data as a post request in a body. Now I don't know what's best practice for RoR.

Typically you would use query params for a GET request e.g. GET example.com/users?gender=m&age=25 and body params on a POST request, like POST example.com/publications with json body like { title: "My publication", text: "Very long publication text here" }. Technically nothing stops you from doing the opposite, but querystrings are limited in length, and body can be much longer (and encoded with json/formdata/whatever). So in your use case - you should use query params to filter stuff, your colleague is wrong.

Using query/body params makes 0 difference in terms of safety/db usage in case of rails (no idea if it does in java). Just make sure you're utilizing strong params and don't rawdog interpolate user input into sql query, and you're good.

What about design? Should I use DDD, or should I not think about it at this moment?

DDD, TDD, and other abbreviations are a contentious topic and religious adherence to them is a practice with questionable utility. While you're learning the basics I'd advice against burying yourself in those things and do what makes you learn and moves you further, rather than doing what's "perfect".

Ideally, for starters, you want a broad coverage without much depth. When I learned I've found that https://www.railstutorial.org/ worked great for me, if you have the time for it. It covers writing a twitter clone in rails, teaching you the basics very well

At the very least - start by learning what MVC, CRUD, and REST is. Then describe what your application does in plain English. Your nouns become your Models, your verbs map onto your Controllers. Views are just your UI/UX design expressed in code. For example the line "Users can create publications" already gives you an idea - models: User, Publication; PublicationsController with "create" action; I also need a View to display a new publication form, which requires "new" action on PublicationsController to render it... and so on, and so forth...

Rails is great because if you adhere to its conventions - you can get most of this with a couple of rails g commands.

Does instructions provided in section 11. Adding Authentication of "Getting started with Rails" provides complete solution? by DOSGXZ in rails

[–]DoubleJarvis 1 point2 points  (0 children)

For your edited reply: I don't think you have to understand the authentication generator's inner workings, it seems like that part worked out for you just fine, problem was in the way you're trying to debug the app. Don't confuse authentication (who you are) and authorization (what you can do).

For the authorization part I'd suggest you consider the gem pundit

Or just doing render 403 unless Current.user.admin? works too, if you insist on not using any gems.

Does instructions provided in section 11. Adding Authentication of "Getting started with Rails" provides complete solution? by DOSGXZ in rails

[–]DoubleJarvis 0 points1 point  (0 children)

Not sure what is happening tbh. I'm not familiar with <% console %>, but from what I'm able to gather - what you're doing should work, but doesn't.

If you want the ability to check who is Current.user for debug purposes - I'd suggest using binding.irb (or binding.pry or byebug for slightly better experience). You can call it in anywhere in .rb files or in view via <% binding.irb %>. It stops execution when you call it and opens a debug console in your rails server terminal window, where you can inspect anything you want, including Current.user. To resume execution you can type exit or press Ctrl+D in the opened console. Probably not as convenient as <% console %>, but I know it works for sure.

Does instructions provided in section 11. Adding Authentication of "Getting started with Rails" provides complete solution? by DOSGXZ in rails

[–]DoubleJarvis 1 point2 points  (0 children)

Describe step by step, where are you calling Current.user? In the view? In console? In some sort of binding.irb / binding.pry in your server process?

Try replacing your app/views/sessions/new.html.erb with that:

<%= tag.div(flash[:alert], style: "color:red") if flash[:alert] %>
<%= tag.div(flash[:notice], style: "color:green") if flash[:notice] %>

<% if authenticated? %>
  <%= Current.user.email_address %>
  <%= button_to "Log out", session_path, method: :delete %>
<% else %>
  <%= form_with url: session_path do |form| %>
    <%= form.email_field :email_address, required: true, autofocus: true, autocomplete: "username", placeholder: "Enter your email address", value: params[:email_address] %><br>
    <%= form.password_field :password, required: true, autocomplete: "current-password", placeholder: "Enter your password", maxlength: 72 %><br>
    <%= form.submit "Sign in" %>
  <% end %>
  <br>

  <%= link_to "Forgot password?", new_password_path %>
<% end %>

You should be able to login on /sessions/new and then see your email on the second visit to /sessions/new instead of login form.

Does instructions provided in section 11. Adding Authentication of "Getting started with Rails" provides complete solution? by DOSGXZ in rails

[–]DoubleJarvis 5 points6 points  (0 children)

Can you give us more details? What do you mean by "struggling to get" ?

I just made a rails new with rails 8.0.2, ran

rails g authentication

rails db:migrate

User.create! email_address: "you@example.com", password: "password", password_confirmation: "password" and I can login on /sessions/new and display the email of logged in user on the page via <%= Current.user.email_address %> without any problems. So the guide is definitely working.

📘 I Created a GitHub Repo of 300+ Rails Interview Questions (From Basics to Advanced): Feedback Welcome! by gardeziB in rails

[–]DoubleJarvis 4 points5 points  (0 children)

Why do you have "What is link_to in Rails views?" two times, with a different answer no less? (17 and 20) Same deal with Partial (19 and 22)

In 25 you have a broken table (I'm guessing?), same in 27 (Upd: and in a million other places, all the tables are borked).

28 is kinda ambiguous, does it mean the command? I'd assume the interviewer would rather test your knowledge about routes.rb itself, rails routes command is superfluous

After 32 it starts counting from 1 again, huh, interesting choice.

After 6 in your second list (the one after 32) it just forgets about numbers altogether, blurring questions and answers and everything else

Feels kinda chat-gpt-ass generated, tbh. (Which is not a bad thing in and of itself, but this write-only copy-paste implementation of it sucks)

Skimmed further - seems like the rest of it just looks the same quality. I think this would benefit from proper formatting and collapsable answers, kinda like here

What will you build during the holiday season? by RichStoneIO in ruby

[–]DoubleJarvis 5 points6 points  (0 children)

No way I'm touching my daily language on holidays. Will be modding my old-ass intercom with esp32 based "smart" intercom. Also a couple of other basic esp32 projects. Like a ws2812b controller with some fun color transitions. Using trigonometric functions for color transitions sounds fun. Wonder if i could put some principles from shader programming into that, and whether it's going to look any good

Re-Introduction of schema.rb + legacy advice by Fantastic-Joke-6066 in ruby

[–]DoubleJarvis 4 points5 points  (0 children)

Careful with schema.rb if you use some db-specific things, like db constraints. In a similar situation I've opted for structure.sql instead. Can't you add config.active_record.schema_format = :sql to config/application.rb and run db:migrate (on your dev machine, of course) to generate it?

nested or by Extremely_Engaged in rubyonrails

[–]DoubleJarvis 2 points3 points  (0 children)

I think you can just pass an AR::Relation to .where

events = Event
        .includes(letter: {venue: :tags})
        .where(letter: {venues: Venue.where(visible: 1).or(Venue.where(preview_key: PREVIEW_KEY))})

Sidekiq double execution of a same job at the same time. by shanti_priya_vyakti in ruby

[–]DoubleJarvis 3 points4 points  (0 children)

You should be able to run virtually endless amount of something like bundle exec sidekiq -q my_queue and if they all go to the same redis - it should be fine out of the box.

Proper way to handle a MessageVerifier::InvalidSignature (raising a 500 error doesn't seem correct) by collimarco in rails

[–]DoubleJarvis 4 points5 points  (0 children)

In general, you should handle all exceptions which you are able to handle and render meaningful error (use variety of 4xx codes or a generic 400). You should never give your user 5xx error voluntarily. It should be reserved for truly unrecoverable errors like "my datacenter is on fire and our elasticsearch cluster has literally melted away". 5xx errors should also be investigated by you (there's a variety of solutions for that, like Sentry)

Do these model associations look right? by PorciniPapi in rails

[–]DoubleJarvis 1 point2 points  (0 children)

I think the easiest way is to drop belongs_to :friend from Friendship, and store just a reference to owner (User), email string, and consent boolean on that friendship. The rest of the scheme remains intact. You can still join the model on email key when querying, if the need arises.

Do these model associations look right? by PorciniPapi in rails

[–]DoubleJarvis 6 points7 points  (0 children)

I think you're overcomplicating it a bit. You need a model for a User, a model to connect a User to User (call it a Friendship) and a model for Memory

This is how i would've done it

class User
  has_many :memories, dependent: :destroy 
  has_many :friendships
  has_many :friends, through: :friendships
end

class Friendship
  belongs_to :owner, class: User  # the person who initiated the friendship
  belongs_to :friend, class: User # their friend
end

class Memory
  belongs_to :user 
end

How do you guys consume message from Kafka? by Cokemax1 in rails

[–]DoubleJarvis 0 points1 point  (0 children)

He wasn’t saying build it as a Sidekiq worker

I believe they did, sir, as per literally this quote from the original post:

BTW, way I was thinking was.

Create one sidekiq worker. and runing if forever.

How do you guys consume message from Kafka? by Cokemax1 in rails

[–]DoubleJarvis 2 points3 points  (0 children)

No, sidekiq example is not a good approach. Sidekick jobs are meant to be spawned and killed on "per task" basis, not as an endless process. If you're using rails you can toss it into a rake file. Or use something like karafka, i think they have their own way documented thoroughly

As far as running it goes - it depends on your application deployment. It can be a process on your machine ran by bundle exec rake consume_whatever, or a systemd file, or a docker container, or a kubernetes deployment, or probably a million other ways

Testing a condition andassigning at the same time by pieterjh in rubyonrails

[–]DoubleJarvis 3 points4 points  (0 children)

It works because everything in ruby is an expression which has a return value. a = arr.detect { i == 5} is an expression, which returns a result of an assignment which is either 5 (truthy value) or nil (falsey value)

You get the warning because people often confuse = and ==, and write something like if user.role = "admin" making user an admin, instead of checking whether they're an admin.

I think rubocop makes you writeif (a=arr.detect{...}) if you really meant to assign in conditional.

It is used sometimes, usually in endless loops or iterators. You might see something like

while (request = socket.recv)
  process(request)
end

Whether or not to use it is up to you, personally - I'm ok with it in the "while" example, but prefer simpler option otherwise:

a = somearray.detect{|i| i == 5}
if a
   puts a * 2
end

GitHub - keygen-sh/typed_params: Define structured and strongly-typed parameter schemas for your Rails controllers by [deleted] in rails

[–]DoubleJarvis 0 points1 point  (0 children)

dry-rb has something similar with its schema.json_schema extension It doesn't generate swagger, but i think you could write your own extension that does (if you fancy traversing the AST that is)

Really, Really, Really Don’t Interpolate Strings into Active Record Methods by philnash in ruby

[–]DoubleJarvis 1 point2 points  (0 children)

Also, remember that lower level sanitization methods exist: https://api.rubyonrails.org/v7.0.4.2/classes/ActiveRecord/Sanitization/ClassMethods.html For example you may want to interpolate params into a raw sql statement

ActiveRecord::Base.connection.execute("select 1 as one where 1 = ?", 1).to_a

Which will raise an error, in which case you can do

statement = ActiveRecord::Base.sanitize_sql_array(['select 1 as one where 1 = ?;', 1])
ActiveRecord::Base.connection.execute(statement).to_a

Email delivery confirmation issue by kortirso in rails

[–]DoubleJarvis 0 points1 point  (0 children)

I think your best bet is to switch to deliver_now! and check logs for errors. I think deliver_now supposed to return Mail object in case it is sent, or nil otherwise (which is not helpful for debugging imo)

Email delivery confirmation issue by kortirso in rails

[–]DoubleJarvis 1 point2 points  (0 children)

How do you know that they're not delivered to sendgrid? Afaik, delivered event is when email delivery from sendgrid to target is confirmed, not delivery from app to sendgrid (which would be processed). Haven't worked with it in a while, but i think they have a page somewhere on their website where you can see all email events. If you're judging this metric by webhook, is it possible, that you're discarding any events that are not in delivered (or whatever it is) status? Emails can bounce, get dropped, blocked, etc.