-
Predicate Methods
A commonly used definition of a predicate method is a method that returns a boolean value. In Ruby, the convention is to end the method name with a question mark.
A predicate method should return
true
orfalse
. (In the reference article, the author mentions that some people instead advocate for a ‘truthy’ value.)0.zero? # => true 1.zero? # => false
defined?
in Ruby might appear to be an exception to the convention as it does not return true or false, butdefined?
an operator, not a method.In Rails, there is a “getter” method generated for each database column by default, like Item#returns_accepted. As a convenience, a question mark method (Item#returns_accepted?) is also generated for boolean database columns which behaves mostly the same but it also converts nil to false.
references
The Elements of Ruby Style: Predicate Methods
19 Mar 2024 -
Rails seeds
A seeds file is a great addition to a new Rails project. Seed data will allow you to populate your developing app quickly, and unlike manually entering sample data, a seeds file can be run over and over as you work.
When working on an existing code base, creating seed data is a safe way to learn the data model. And
faker
can be added to generate data for performance testing.faker initial seeds replant
# db/seeds.rb require "faker" return if Rails.env.production? # in case someone runs db:seed instead of db:seed:replant 10.times do User.create!( Faker::Name::name, password: "Not2secret", Faker::Internet.email ) end
# Initial creating and seeding of database $ rails db:seed # or $ rails db:seed:replant
references
Rails 6 adds db:seed:replant task
11 Nov 2023 -
Copilot language translation
In a recent Hackathon, content needed to be translated into multiple languages. Initially, web based translation services were used and a small sample was prepared to be used as a seed file.
It was surprising to find that Github Copilot can help you translate languages!
hindi.phrases.create!(label: "I need assistance", phrase: "मुझे सहायता की ज़रूरत है", pronunciation: "mujhe sahaayata kee jaroorat hai") hindi.phrases.create!(label: "Dial 911", # then tab and Copilot will suggest: hindi.phrases.create!(label: "Dial 911", phrase: "911 डायल करें", pronunciation: "911 daayal karen")
Much faster than looking up individually and generated 12 translations in 10 languages in minutes.
28 Oct 2023