At Codemancers, we believe every day is an opportunity to grow. This section is where our team shares bite-sized discoveries, technical breakthroughs and fascinating nuggets of wisdom we've stumbled upon in our work.
Published
Author
Sujay
Rails templates accept any locals as arguments. However, starting from Rails 7.1, we can restrict which locals a template must accept using "Strict Locals".
I wonder who in the world wrote this snippet!!! :)
#javascript #browser
Published
Author
Syed
Ransack adds several class methods to ActiveRecord::Base for managing search and sort capabilities. These methods allow us to define which attributes, associations, and scopes are accessible through Ransack queries, thus enhancing security and control.
ransackable_attributes: Defines which model attributes can be used in Ransack searches. For example, only the order_number, status, and business_unit fields can be used in Ransack searches.
Code
def self.ransackable_attributes(auth_object = nil) %w[order_number status business_unit] end
ransackable_associations: Specifies which model associations are accessible for searching. For examle, only the customer and vendor associations are allowed for searching.
Code
def self.ransackable_associations(auth_object = nil) %w[customer vendor] end
ransortable_attributes: Lists which attributes can be used for sorting results. In this example, sorting is allowed only by order_number and created_at
Code
def self.ransortable_attributes(auth_object = nil) %w[order_number created_at] end
ransackable_scopes: Determines which custom scopes can be applied in searches.
#rails #ransack #search
Published
Author
Sujay
In postgres, current_setting() function is used to get the value of a configuration parameter.
Code
Set rls.tenant_id = 1;SETselect current_setting('rls.tenant_id'); current_setting----------------- 1(1 row)
#postgres
Published
Author
Syed
Namespaces in Rails help organize our application by grouping related controllers, models, and views into separate directories. Using namespaces with scaffolding keeps our codebase structured and manageable, especially in larger applications.
This will create files under the Order namespace, including controllers, models, and views. This approach keeps our codebase structured, with Order as a namespace, making it easier to manage related components and maintain clarity in larger applications.
Lesson: Even a browser can cause browser compatibility issues.
#regex #browserCompatibility #safari #javascript
Published
Author
Sachin Kabadi
System Analyst
How to override models in parent application by reopening existing Rails engine classes. This can be done by organising overrides in a dedicated directory (e.g., app/overrides), ignoring this directory in the autoloader, and preloading the overrides in a to_prepare callback.
Ruby
# config/application.rbmodule MyApp class Application < Rails::Application # ... overrides = "#{Rails.root}/app/overrides" Rails.autoloaders.main.ignore(overrides) config.to_prepare do Dir.glob("#{overrides}/**/*_override.rb").sort.each do |override| load override end end endend
To override an engine model, such as Blog::Article:
Ruby
# Blog/app/models/blog/article.rbmodule Blog class Article < ApplicationRecord # ... endend
Create a file that reopens the class:
Ruby
# MyApp/app/overrides/models/blog/article_override.rbBlog::Article.class_eval do # ...end
Using class_eval ensures we are reopening the class or module, not redefining it.
#rails #rails-engines
Published
Author
Sujay
Remove the published gem from rubygems using
Ruby
gem yank GEM -v VERSION
#rails #rubygems
Published
Author
Satya
while using form.file_field for file attachments we can restrict the file type to any type if we want. For eg: if we want to accept file of type image then we can pass accept attribute.
Note: This will disable other file types in your local file dialog while enabling the image files only 🪄 . #rails , #active-storage
Published
Author
Sujay
To ensure a dependency is installed with the engine during gem install, it must be specified within the Gem::Specification block inside the engine's .gemspec file (e.g., blog.gemspec for an engine named Blog, located at the root)
Code
s.add_dependency "pagy"
#rails #rails-engines
Published
Author
Syed
In Rails, gems are libraries that add specific functionality to a Rails application. They can be used across different projects and typically do not have their own structure or generators. Examples include devise for authentication and nokogiri for XML parsing.
Engines, on the other hand, are miniature Rails applications that can have their own routes, controllers, models, and views. They are used to encapsulate and modularize specific features or components within a Rails app. An engine can be packaged as a gem, but it provides more extensive, self-contained functionality compared to a typical gem.
#rails
Published
Author
Sujay
A Rails engine is a pattern used to modularize a Rails application. These engines are self-contained applications with their own models, views, controllers, and routes, allowing them to function autonomously. They can be integrated into a larger Rails application. For example, in an e-commerce application, modules like orders, products, users, and payments can each be separate engines. #rails
Published
Author
Codemancers
Resolving gen_random_uuid() Error with PostgreSQL While Implementing CI When configuring CI with GitHub Actions, I encountered the following error:
Code
PG::UndefinedFunction: ERROR: function gen_random_uuid() does not exist
This error occurred because the gen_random_uuid() function is not available in PostgreSQL versions older than 11. UUID generation functions were only available through external modules like uuid-ossp and pgcrypto in these older versions.
To resolve this issue, I upgraded to PostgreSQL 13, which includes the gen_random_uuid() function to generate version-4 UUIDs. After upgrading, the error was resolved.
#rails #postgresql #uuid #ci-cd #github-actions
Published
Author
Adithya Hebbar
System Analyst
Jupyter Labs
• To install Jupyter Labs in Mac using Homebrew:
Python
brew install jupyterlab
• To run Jupyter lab:
Python
jupyter lab
This will open JupyterLab in your default web browser.
#python #homebrew
Published
Author
Giritharan
System Analyst
The fields_for helper in Rails creates form bindings without rendering a <form> tag. This is particularly useful for rendering fields for additional model objects within a single form.
Imagine you have a Book model with an associated Author model. You can create a single form for both the Book and Author models using the fields_for helper.
Ruby
<%= form_with model: @book do |book_form| %> <%= book_form.text_field :title %> <%= book_form.text_area :description %> <%= fields_for :author, @book.author do |author_form| %> <%= author_form.text_field :name %> <%= author_form.text_field :email %> <% end %><% end %>
#rails #fields-for #rails-view
Published
Author
Codemancers
rails db:prepare in Ruby on Rails, This command sets up and prepares the database for my application, ensuring everything's ready to go, including populating the database. #rails #databasesetup
Published
Author
Soniya Rayabagi
Handling Terraform State Errors with S3 Backend: We use an S3 bucket to store our Terraform state. If Terraform fails to update the state, it creates an errored.tfstate file in your working directory. Reapplying will cause errors because the resources already exist. To fix this, push the errored state back to S3: terraform state push errored.tfstate
#devops #terraformstateS3 #errorhandling
Published
Author
Syed
In Ruby, exception handling is done using begin, rescue, ensure, and end blocks. Here's a brief overview of how they work in a general Ruby context:
Ruby
begin # Code that might raise an exceptionrescue SomeExceptionClass => e # Code that handles the exceptionensure # Code that will always run, regardless of whether an exception was raisedend
begin: Marks the beginning of a block of code that might raise exceptions.
rescue: Specifies what to do if a specific exception is raised. We can rescue multiple exception types by chaining rescue blocks.
ensure: An optional block that will always execute, regardless of whether an exception was raised or rescued. It's useful for cleanup code that must run no matter what.
#ruby #rails
Published
Author
Syed
Using Ruby's built-in URI::MailTo::EMAIL_REGEXP for email validation is generally better than using a custom regular expression due to its robustness, reliability, and maintenance by the Ruby core team.
Ruby
class User < ApplicationRecord has_secure_password validates :name, presence: true # Using a custom regular expression for email validation validates :email, presence: true, format: { with: /\\A[^@\\s]+@[^@\\s]+\\z/ }, uniqueness: true # Using Ruby's built-in URI::MailTo::EMAIL_REGEXP for email validation validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }, uniqueness: trueend
#ruby #regex #rails
Published
Author
Syed
Fixing Image Rendering in Rails with Active Storage How to fix the error PG::UndefinedTable: ERROR: relation "active_storage_attachments" does not exist
This error occurs because Active Storage in Rails relies on specific database tables (e.g., active_storage_attachments and active_storage_blobs) to store metadata about attached files. If these tables do not exist, Rails cannot store or retrieve the necessary metadata for file attachments, resulting in the mentioned error.
By following these steps, we ensure that the necessary Active Storage tables are created, allowing Rails to store and retrieve image metadata correctly.
Run Active Storage Installation:
Ruby
rails active_storage:install
Migrate the Database:
Ruby
rails db:migrate
Restart the Rails Server:
Ruby
rails server
Then in views we can simply use the helper and render the image