Code Snippets

Home » snippets
ActiveRecord Strict Loading

Improve performance by not lazy loading associations if not explicitly [md] ```ruby class User < ActiveRecord::Base has_many :comments, strict_loading: true end # loading u = User.first u.comments # => Raise ActiveRecord::StrictLoadingViolationError u = User.includes(:comments).first u.comments # => will work ``` [/md]

React Conditional Rending Components

When writing react code avoid using conditional components like so: [md] ```js export default function Scores({score}) { return ( {score < 30 ? "👎" : score < 70 && score >= 30 ? "👍" : "👌"} ) } ``` [/md] They are difficult to read and very difficult to scale Read more...

Parse JSON with Object Class

Nice way to parse JSON in Ruby, using a poorly documented object_class option (found on SO). Far easier to dig then. credits to @ShinoKouda

Run Sidekiq Seamlessly Within Rails

Now you can run Rails and Sidekiq with simple "rails s" command in the same process. Upgrade to Sidekiq 7 Add settings to the Puma config credits to @kirill_shevch

Debug Rails Controllers from Console

When working with Ruby objects it's often helpful to call individual methods in the console. This is helpful in development and debugging. Rails allows you to do the same in controllers. Infact you can create the same type of session as the one used in integration tests, allowing you to Read more...

Where Clause Along with Associations in Rails

As a developer you will struggle with models associations but sometimes you may need only some record from an associations, and when you need it frequently you can create a separate association like so: has_many :remote_employees, -> {where(remote:true)}, class_name: 'Employee'

ActiveRecord greater/less Than Comparison

Many times you will find yourself query for some records in between of a range being it a date range or a numeric range. ActiveRecord allows you to use a Ruby range or incomplete range to query data in the database.

Rails Console Sandbox mode

Many times you have to test your models in the rails console and you may want to not pollute your development database with all your experiments. Rails has you covered. Launching the rails console with the --sandbox option will allow you to do whatever your want with your models because Read more...